标签:mem mis inf bfs pst nbsp ted miss ali
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 49149 | Accepted: 26684 |
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 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 5 using namespace std; 6 7 typedef pair<int,int> P; 8 9 const int INF = 1e8; 10 11 const int N=5,M=5; 12 int maze[N][M],d[N][M]; 13 int sx=0,sy=0; 14 int gx=4,gy=4; 15 16 int dx[2]={0,1},dy[2]={1,0}; 17 18 struct 19 { 20 int x; 21 int y; 22 }pre[N][M]; 23 24 void bfs() 25 { 26 // 初始化队列 27 queue<P> que; 28 // 初始化距离 29 for(int i=0;i<N;++i) 30 { 31 for(int j=0;j<M;++j) 32 { 33 d[i][j]=INF; 34 } 35 } 36 d[0][0]=0; 37 que.push(P(0,0)); 38 // 39 while(que.size()) 40 { 41 // 取出元素 42 P p=que.front(); 43 que.pop(); 44 // 找到终点 45 if(p.first==gx && p.second==gy) 46 { 47 break; 48 } 49 // 左和下找其余可行顶点 50 for(int i=0;i<2;++i) 51 { 52 53 int nx=p.first+dx[i]; 54 int ny=p.second+dy[i]; 55 //printf("%d %d\n",nx,ny); 56 if(nx>=0 && nx<N && ny>=0 && ny<M && maze[nx][ny]==0 && d[nx][ny]==INF) 57 { 58 que.push(P(nx,ny)); 59 d[nx][ny]=d[p.first][p.second]+1; 60 // 记录前一节点 61 pre[nx][ny].x=p.first; 62 pre[nx][ny].y=p.second; 63 } 64 } 65 } 66 67 } 68 69 void dfs(int nx,int ny) 70 { 71 if(pre[nx][ny].x==0 && pre[nx][ny].y==0) 72 { 73 printf("(0, 0)\n"); 74 printf("(%d, %d)\n",nx,ny); 75 return; 76 } 77 78 dfs(pre[nx][ny].x,pre[nx][ny].y); 79 printf("(%d, %d)\n",nx,ny); 80 81 } 82 83 void solve() 84 { 85 bfs(); 86 if(d[gx][gy]==INF) 87 { 88 printf("NO\n"); 89 } 90 else 91 { 92 dfs(gx,gy); 93 } 94 } 95 96 int main() 97 { 98 for(int i=0;i<N;++i) 99 { 100 for(int j=0;j<M;++j) 101 { 102 scanf("%d",&maze[i][j]); 103 } 104 } 105 solve(); 106 return 0; 107 }
标签:mem mis inf bfs pst nbsp ted miss ali
原文地址:https://www.cnblogs.com/jishuren/p/12244718.html