题意很简单,中文题,我就不解释了,直接看看代码吧,很水的一个BFS题。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
int x, y, father;
}edge[60];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int s[6][6], vis[6][6];
bool in(int x,int y)
{
return x >= 0 && y >= 0 && x < 5 && y < 5;
}
void dfs(int x)
{
if(x != -1)
{
dfs(edge[x].father);
cout <<"(" <<edge[x].x << ", " << edge[x].y << ")"<< endl;
}
}
bool bfs()
{
memset(vis, 0, sizeof(vis));
int front = 0, ans = 0;
edge[ans].x = 0;
edge[ans].y = 0;
edge[ans++].father = -1;
while(front < ans) // 用front记录当前是第几个元素, ans 记录总共有多少个元素。
{
int x, y , father;
x = edge[front].x;
y = edge[front].y;
father = edge[front].father;
if(x == 4 && y == 4)
{
dfs(father);
break;
}
if(vis[x][y] == 1)
{
front++;
continue;
}
vis[x][y] = 1;
for(int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if(in(xx,yy) && s[xx][yy] == 0)
{
edge[ans].x = xx;
edge[ans].y = yy;
edge[ans++].father = front;
}
}
front++;
}
return 0;
}
int main()
{
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
cin >> s[i][j];
}
}
bfs();
cout << "(4, 4)" << endl;
return 0;
}