Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 13824 | Accepted: 8256 |
Description
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
Input
Output
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
分析:1.dfs解决,记录路径方便,但慢。。。
code:
#include <cstdio> #include <iostream> #include <cstring> using namespace std; typedef long long ll; typedef struct{ int x,y; }data; int maze[10][10]; int dx[]={0,1,0,-1},dy[]={1,0,-1,0}; int sout=0,min=100000; int len=100000; int sol=0; data way[25][30]; int vis[10][10]; void dfs(int x,int y,int wal) { way[sol][wal].x=x,way[sol][wal].y=y; if(x==4&&y==4) { if(len>wal) { sout=sol; len=wal; } sol++; } for(int i=0;i<4;i++) { int a=x+dx[i],b=y+dy[i]; if( 0 <= a && a < 5 && 0 <= b && b < 5 && maze[a][b]==0 && vis[a][b]==0 ) { vis[a][b]=1; dfs(a,b,wal+1); vis[a][b]=0; } } } int main(void) { memset(vis,0,sizeof vis); for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&maze[i][j]); vis[0][0]=1; dfs(0,0,0); for(int i=0;i<=len;i++) { printf("(%d, %d)\n",way[sout][i].x,way[sout][i].y); } }
分析:2.bfs解决,记录路径使用记录父节点的方法,并递归输出
code:
#include <cstdio> #include <iostream> #include <cstring> using namespace std; typedef long long ll; typedef struct{ int x,y; int par; }data; int vis[1005][1005],dx[]={ 0,1,0,-1 },dy[]={ 1,0,-1,0 }; int maze[1005][1005]; data wal[2005]; void prin(int pare) { if(wal[pare].par!=-1) { prin(wal[pare].par); printf("(%d, %d)\n",wal[pare].x,wal[pare].y); } else printf("(%d, %d)\n",wal[pare].x,wal[pare].y); } void bfs() { int sol=1,head=0; while ( head < sol ) { for(int i=0;i<4;i++) { int a=wal[head].x+dx[i],b=wal[head].y+dy[i]; if ( 0 <= a && a < 5 && 0 <= b && b < 5 && vis[a][b]==0 ) { if( a==4 && b==4) { wal[sol].x=a; wal[sol].y=b; wal[sol].par=head; prin(sol); // return ; } if ( maze[a][b] == 0 ) { vis[a][b]=1; wal[sol].x=a; wal[sol].y=b; wal[sol].par=head; sol++; } } } head++; } } int main(void) { for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&maze[i][j]); wal[0].x=0,wal[0].y=0,wal[0].par=-1; vis[1][1]=1; bfs(); }