题目链接:POJ 3984
题意:走迷宫。
分析:在结构体里,设置一个字符串数组用以记录相应移动即可。
CODE:
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <cstdio>
#include <algorithm>
using namespace std;
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
int a[5][5], vis[5][5], r, c;
int valid(int x, int y)
{
if (x < 0 || y < 0 || x >= 5 || y >= 5 || vis[x][y]||a[x][y]) return 0;
return 1;
}
struct Node {
int x, y, step;
char s[25][10];
}cur,nextnode;
void bfs()
{
memset(vis, 0, sizeof(vis));
queue<Node> q;
cur.x = cur.y = cur.step = 0;
strcpy(cur.s[0], "(0, 0)");//注意这里第二个0之前有一个空格
q.push(cur);
while (!q.empty())
{
cur = q.front();
q.pop();
for (int i = 0;i < 4;i++)
{
r = cur.x + dir[i][0];
c = cur.y + dir[i][1];
if (!valid(r, c)) continue;
nextnode.x = r;
nextnode.y = c;
nextnode.step = cur.step + 1;
for (int j = 0;j <= cur.step;j++)
strcpy(nextnode.s[j], cur.s[j]);
sprintf(nextnode.s[nextnode.step], "(%d, %d)", r, c);//注意c之前有一个空格
if (r == 4 && c == 4)
{
for (int j = 0;j <= nextnode.step;j++)
puts(nextnode.s[j]);
return;
}
q.push(nextnode);
}
}
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
for (int i = 0;i < 5;i++) {
for (int j = 0;j < 5;j++) {
cin >> a[i][j];
}
}
bfs();
return 0;
}