BFS用栈弹出路径

来源:互联网 发布:矩阵的秩的物理意义 编辑:程序博客网 时间:2024/06/10 22:06
#include <iostream>
#include <stack>
#include <queue>
using namespace std;


struct p 
{
int x, y, d;
};




int vis[100][100], dis[100][100],fy[100][100],fx[100][100];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};


int main()
{
char g[100][100];
queue <p> q;
stack <p> s;
int m, n, i, j; 
int sx, sy, ex, ey;
int xx, yy;
cin >> m >> n;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cin >> g[i][j];
vis[i][j] = 0;
}
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
if(g[i][j] == 's')
{
sx = j;
sy = i;
}
if(g[i][j] == 't')
{
ex = j;
ey = i;
}
}
}
p temp, cur;
temp.x = sx;
temp.y = sy;
temp.d = 0;
q.push(temp);
while(!q.empty())
{
cur = q.front();
q.pop();
for(i = 0; i < 4; i++)
{
yy = cur.y + dir[i][0];
xx = cur.x + dir[i][1];
if(g[yy][xx] != '#' && vis[yy][xx] == 0 && m > xx && xx >= 0 && n > yy && yy >= 0)
{
temp.x = xx;
temp.y = yy;
temp.d = cur.d + 1;
fy[yy][xx]=cur.y;
                fx[yy][xx]=cur.x;
dis[yy][xx] = cur.d + 1;

q.push(temp);
}
vis[cur.y][cur.x] = 1;

}
}
if(vis[ey][ex] == 0)
{
cout << "NO" << endl;
}
else
{
cout << "Yes" << endl;
cout << dis[ey][ex] << endl;
}
temp.x = ex;
temp.y = ey;
yy=ey;
xx=ex;
s.push(temp);
while(g[yy][xx]!='s')
{
temp.y=fy[yy][xx];
temp.x=fx[yy][xx];
s.push(temp);
yy=temp.y;
xx=temp.x;
}
while(!s.empty())
{
temp=s.top();
cout<<"("<<temp.x<<","<<temp.y<<")"<<endl;
s.pop();
}
return 0;
}
原创粉丝点击