题解 | #迷宫问题#dfs解法 !可以根据输入参数step和vector得出当路径不唯一时输出最短路径
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include<iostream>
#include<vector>
//#include<algorithm>
#include<cstdio>
using namespace std;
int a[100][100] ;
int v[100][100] = {0};
int minx = 999;
int n=0,m=0;
int x,y,p,q;
int nx =0,ny=0;
vector<int> xx,yy;
void dfs(int x,int y,int step)
{
if(x == p && y == q)
{
for(int i=0;i<yy.size();i++)
cout<<'('<<xx[i]<<','<<yy[i]<<')'<<endl;
return;
}
if(a[x][y+1] == 0 && v[x][y+1] == 0)
{
v[x][y+1] = 1;
ny++;
xx.push_back(nx);
yy.push_back(ny);
dfs(x,y+1,step+1);
xx.pop_back();
yy.pop_back();
ny--;
v[x][y+1] = 0;
}
if(a[x+1][y] == 0 && v[x+1][y] == 0)
{
v[x+1][y] = 1;
nx +=1;
xx.push_back(nx);
yy.push_back(ny);
dfs(x+1,y,step+1);
xx.pop_back();
yy.pop_back();
nx--;
v[x+1][y] = 0;
}
if(a[x][y-1] == 0 && v[x][y-1] == 0)
{
v[x][y-1] = 1;
ny-=1;
xx.push_back(nx);
yy.push_back(ny);
dfs(x,y-1,step+1);
xx.pop_back();
yy.pop_back();
ny++;
v[x][y-1] = 0;
}
if(a[x-1][y] == 0 && v[x-1][y] == 0)
{
v[x-1][y] = 1;
nx -=1;
xx.push_back(nx);
yy.push_back(ny);
dfs(x-1,y,step+1);
xx.pop_back();
yy.pop_back();
nx++;
v[x-1][y] = 0;
}
return;
}
int main(void)
{
scanf("%d%d",&m,&n);
for(int i=0;i<=99;i++)
{
for(int j=0;j<=99;j++)
{
a[i][j] =3;
}
}
int i=1,j=1;
for(;i<=m;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
p=m;
q=n;
x=1;
y=1;
nx=0;ny=0;
v[x][y] = 1;
cout<<"(0,0)"<<endl;
dfs(x,y,0);
return 0;
}