poj dfs相关之3984 迷宫问题
这道题可以用dfs和bfs
1、由于数据保证有唯一解,所以dfs也可以:
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
int n, m, i, j, k, flag, count;
int data[5][5], vis[5][5];
int dir[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
struct Path
{
int a, b;
};
vector<Path> que;
void dfs(int x, int y)
{
int i, xx, yy;
if (flag)
return;
if (x == 4 && y == 4){
flag = 1;
int t = 0;
while (t < que.size())
{
printf("(%d, %d)\n", que[t].a, que[t].b);
t++;
}
return;
}
for (i = 0; i<4; i++)
{
xx = x + dir[i][0];
yy = y + dir[i][1];
if (vis[xx][yy] == 0 && data[xx][yy] == 0 && xx >= 0 && xx<5 && yy >= 0 && yy<5)
{
vis[xx][yy] = 1;
Path tmp;
tmp.a = xx;
tmp.b = yy;
que.push_back(tmp);
dfs(xx, yy);
que.pop_back();
vis[xx][yy] = 0;
}
}
}
int main()
{
freopen("1.txt", "r", stdin);
for (i = 0; i<5; i++)
for (j = 0; j<5; j++)
scanf("%d", &data[i][j]);
memset(vis, 0, sizeof(vis));
Path tmp;
tmp.a = 0;
tmp.b = 0;
que.push_back(tmp);
flag = 0;
dfs(0, 0);
return 0;
}
2、bfs:
代码比较不简洁,需要用一个father数组来存储路径
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int n, k, ans;
bool arr[5][5], mark[5][5];
int dir[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
struct point
{
int a;
int b;
};
queue<point> que;
vector<point> output;
point father[5][5];
void bfs()
{
int i, x, y;
while (!que.empty())
{
point tmp;
tmp = que.front();
que.pop();
for (i = 0; i < 4; i++)
{
x = tmp.a + dir[i][0];
y = tmp.b + dir[i][1];
if (x == 4 && y == 4)
{
father[4][4] = tmp;
return;
}
else if (x >= 0 && y >= 0 && x < 5 && y < 5)
{
if (!mark[x][y] && !arr[x][y])
{
mark[x][y] = 1;
point curr;
curr.a = x;
curr.b = y;
father[x][y] = tmp;
que.push(curr);
}
}
}
}
}
int main()
{
int i, j, tmp1, tmp2;
memset(mark, 0, sizeof(mark));
memset(arr, 1, sizeof(arr));
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
scanf("%d", &arr[i][j]);
point tmp;
tmp.a = 0;
tmp.b = 0;
que.push(tmp);
mark[0][0] = 1;
bfs();
i = 4; j = 4;
while (i != 0 || j != 0)
{
point cur;
cur.a = i;
cur.b = j;
output.push_back(cur);
tmp1 = father[i][j].a;
tmp2 = father[i][j].b;
i = tmp1;
j = tmp2;
}
printf("(0, 0)\n");
for (i = output.size() - 1; i >= 0; i--)
printf("(%d, %d)\n", output[i].a, output[i].b);
}