前言:
迷宫求解路径一般使用深度和广搜,【注】广搜可以得到最短路径,因为从遍历的时候可以看出,每个方位不同的试探,最先达到目标的就马上退出故能求得最短路径..
#include <stdio.h>
int n, map[20][20], i, j, step, flag, head, tail;
// 4个方向
int dir[4][2] = {
{0, 1}, {1, 0}, {0, -1}, {-1, 0}
};
// save the pass path
struct Index {
int x;
int y;
} path[200];
struct Bfs {
int x, y;
int parent; // 孩子节点的父节点,用来打印路径
} queue[200];
// 打印路径
void printDFS()
{
for(i=0; i<=step; i++)
printf("%d %d\n", path[i].x, path[i].y);
}
void printBFS()
{
i = tail;
while(i != -1)
{
printf("%d %d\n", queue[i].x, queue[i].y);
i = queue[i].parent;
}
}
// 深度搜索
void dfs(int x, int y)
{
if(flag) return;
int k;
for(k=0; k<4; k++)
{
int x1 = x + dir[k][0], y1 = y + dir[k][1];
if(x1 >= 0 && x1 < n && y1 >=0 && y1 < n && !map[x1][y1])
{
map[x1][y1] = 1;
step ++;
path[step].x = x1;
path[step].y = y1;
if(x1 == n - 1 && y1 == n - 1) {
printDFS();
flag = 1;
return;
}
dfs(x1, y1);
map[x1][y1] = 0;
path[step].x = path[step].y = 0;
step --;
}
}
}
// 广度搜索
void bfs()
{
// {0, 1}, {1, 0}, {0, -1}, {-1, 0}
head = tail = flag = 0;
queue[head].x = queue[head].y = map[0][0];
queue[head].parent = -1;
while(1)
{
// 4 directions
if(!map[queue[head].x][queue[head].y + 1] && isBound(queue[head].x, queue[head].y + 1))
{
map[queue[head].x][queue[head].y + 1] = 1; // 标志当前路径
tail ++;
queue[tail].x = queue[head].x, queue[tail].y = queue[head].y + 1;
queue[tail].parent = head; // 保存当前路径的前一个节点,既父节点
if(queue[head].x == n - 1 && queue[head].y + 1 == n - 1) return; // 满足条件退出
}
if(!map[queue[head].x + 1][queue[head].y] && isBound(queue[head].x + 1, queue[head].y))
{
map[queue[head].x + 1][queue[head].y] = 1;
tail ++;
queue[tail].x = queue[head].x + 1, queue[tail].y = queue[head].y;
queue[tail].parent = head;
if(queue[head].x + 1 == n - 1 && queue[head].y == n - 1) return;
}
if(!map[queue[head].x][queue[head].y - 1] && isBound(queue[head].x, queue[head].y - 1))
{
map[queue[head].x][queue[head].y - 1] = 1;
tail ++;
queue[tail].x = queue[head].x, queue[tail].y = queue[head].y - 1;
queue[tail].parent = head;
if(queue[head].x == n - 1 && queue[head].y - 1 == n - 1) return;
}
if(map[queue[head].x - 1][queue[head].y] && isBound(queue[head].x - 1, queue[head].y))
{
map[queue[head].x - 1][queue[head].y] = 1;
tail ++;
queue[tail].x = queue[head].x - 1, queue[tail].y = queue[head].y;
queue[tail].parent = head;
if(queue[head].x - 1 == n - 1 && queue[head].y == n - 1) return;
}
head ++;
}
flag = 1;
}
// 判断在边界内
int isBound(int i, int j)
{
if(i < n && i >= 0 && j < n && j >= 0)
return 1;
return 0;
}
int main()
{
while(scanf("%d", &n) != EOF)
{
for(i=0; i<n; i++)
{
for(j=0; j<n; j++) scanf("%d", &map[i][j]);
}
/* DFS
step = flag = 0;
path[step].x = path[step].y = 0;
dfs(0, 0);
if(step <= 0) printf("noway");
*/
// BFS
bfs();
if(flag) printf("noway");
else printBFS();
}
return 0;
}
/* 测试数据
5
0 0 1 0 0
0 0 1 0 0
0 0 0 0 1
0 1 1 1 1
0 0 0 0 0
6
0 0 0 0 0 1
0 0 1 1 0 0
0 0 0 0 0 1
0 1 1 0 0 0
0 0 1 0 1 0
1 0 0 0 0 0
*/