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)
分析:
本题为一迷宫,从左上方走到右下方经过的最短路线,典型的bfs问题 先到达就退出 主要是打印路线 可以用一个值来保存经过的最短路线
Ac代码:
#include <iostream> #include<cstring> using namespace std; int top = -1,under = 0,visit[100][2],dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}},queue[100],a[5][5],v,s[100]; void queue_push(int x) { queue[++top] = x; } int queue_pop() { return queue[under++]; } int main() { int i,j; for(i = 0; i < 5; i++) { for(j = 0; j < 5; j++) { cin>>a[i][j]; } } memset(visit,0,sizeof(visit)); queue_push(0); visit[0][0] = 1; while(under<=top) { v = queue_pop(); if(v == 24) break; int x = v/5,y = v%5; for(int i = 0;i < 4;i++) { int px = x+dir[i][0],py = y +dir[i][1]; if(visit[px*5+py][0] == 0&&a[px][py] == 0&&px>=0&&px<5&&py>=0&&py<5) { queue_push(px*5+py); //满足条件添加进数组 visit[px*5+py][0] = 1; //标记已经经过此点 visit[px*5+py][1] = v; //保存路线 } } } for( i = 1,s[0] = 24;s[i-1] != 0; i++ ) { s[i] = visit[s[i-1]][1]; } for( j = i- 1;j >= 0; j--) { cout<<"("<<s[j]/5<<", "<<s[j]%5<<")"<<endl; } return 0; }
原文:http://www.cnblogs.com/LIUWEI123/p/5676858.html