K - 迷宫问题

时间:2023-03-10 05:20:17
K - 迷宫问题
/*
定义一个二维数组: 
int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
这里最短路径好求,BFS即可,但是如何保存路径是个问题,在这里我采用了一次BFS,即从终点向起点搜索同时用stack保存路径上的点。
*/
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
struct node
{
int x;
int y;
int step;
};
int g[][];
int been[][];
int dis[][];
int dir[][]={{,},{,},{-,},{,-}};
stack<node> S;
bool judge(int x,int y)
{
if(!g[x][y]&&!been[x][y]&&x>=&&y>=&&x<&&y<)
return true;
return false;
}
void Read()
{
int i,j;
for(i=;i<;i++)
for(j=;j<;j++)
cin>>g[i][j];
}
int bfs(int i,int j)
{
node a;
a.x = i;
a.y = j;
a.step = ;
been[i][j] = ;
dis[i][j] = ;
queue<node> Q;
Q.push(a);
while(!Q.empty())
{
node temp = Q.front();
Q.pop();
if(temp.x==&&temp.y==)
return temp.step;
for(int i =;i<;i++)
{
if(judge(temp.x+dir[i][],temp.y+dir[i][]))
{
node new_node;
new_node.x = temp.x+dir[i][];
new_node.y = temp.y+dir[i][];
new_node.step = temp.step + ;
been[new_node.x][new_node.y] = ;
Q.push(new_node);
if(dis[new_node.x][new_node.y] > temp.step + )
dis[new_node.x][new_node.y]=temp.step + ;
}
}
}
return -;
}
void route(int i,int j,int d);
int main()
{
int i,j,ans;
for(i = ;i<;i++)
for(j=;j<;j++)
dis[i][j] = ;
Read();
ans = bfs(,);
route(,,ans);
while(!S.empty())
{
node p = S.top();
S.pop();
cout<<'('<<p.x<<','<<' '<<p.y<<')'<<endl;
}
cout<<'('<<<<','<<' '<<<<')'<<endl;
return ;
}
void route(int i,int j,int d)
{
if(i==&&j==)
{
return ;
}
else
{
for(int k =;k<;k++)
{
int r = i+dir[k][],c = j+dir[k][];
if(r>=&&c>=&&r<&&c<&&(dis[r][c]==d-)&&(been[r][c]))
{
node ct;
ct.x = r;
ct.y = c;
S.push(ct);
route(r,c,d-);
}
}
}
return ;
}