入门题
直接bfs
直接上代码
注意判重是0要特别注意,第一个入队列的数据不要玩了标记
#include
#include
#include
#include
using namespace std;
int a[10][10];
int vis[100];
int dir[5][2] = { {1, 0}, {-1, 0}, {0, -1}, {0, 1} };
struct node
{
int x, y;
node(){}
node(int xx, int yy)
{
x = xx; y = yy;
}
};
queue
que; void bfs() { for(int i = 0; i <= 44; i++) vis[i] = -1; while(!que.empty()) que.pop(); que.push( node(0, 0) ); vis[0] = -2; while(!que.empty()) { node tmp = que.front(); que.pop(); for(int i = 0; i < 4; i++) { int x = tmp.x + dir[i][0]; int y = tmp.y + dir[i][1]; if(0 <= x && x < 5 && 0 <= y && y < 5 && !a[x][y] && vis[x*10+y]==-1) { vis[x*10+y] = tmp.x*10+tmp.y; if(x == 4 && y == 4) return; que.push( node(x, y) ); } } } } int prin(int n) { if(n != -2) { prin(vis[n]); printf("(%d, %d)\n", n/10, n%10); } return 0; } int main(void) { int i, j; for(i = 0; i < 5; i++) for(j = 0; j < 5; j++) scanf("%d", &a[i][j]); bfs(); prin(44); return 0; }