Description
定義一個(gè)二維數(shù)組:
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,
};
它表示一個(gè)迷宮,其中的1表示墻壁,0表示可以走的路,只能橫著走或豎著走,不能斜著走,要求編程序找出從左上角到右下角的最短路線。
Input
一個(gè)5 × 5的二維數(shù)組,表示一個(gè)迷宮。數(shù)據(jù)保證有唯一解。
Output
左上角到右下角的最短路徑,格式如樣例所示。
Sample Input
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
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
理解:
0表示可以走的路徑,找到最短的路徑然后把路徑坐標(biāo)挨個(gè)輸出.搜索最佳路徑問題,尤其是最短路徑問題都可以用廣度搜索來解決.
所以不知道的同學(xué)又要去學(xué)習(xí)啦~BFS
代碼部分
#include<iostream>
#include<stack>
using namespace std;
int i,j,ff,num,front,a[5][5],b[5][5],c[5][5];
stack<int>x;
stack<int>y;
void dfs(int i,int j)//這里函數(shù)名命名錯(cuò)了,但是不影響程序運(yùn)行。。。
{
if(a[i][j]==1||i<0||j<0||i>=5||j>=5||b[i][j]==1) return ;
if(c[i][j]==0&&a[i][j]==0&&b[i][j]==0)
{
c[i][j]=ff;
b[i][j]=1;
ff++;
}
dfs(i,j+1);
dfs(i+1,j);
dfs(i-1,j);
dfs(i,j-1);
}
int main()
{
for(i=0;i<5;i++)
for(j=0;j<5;j++)
{
cin>>a[i][j];
b[i][j]=0;
c[i][j]=0;
}
ff=1;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]==0)
{dfs(i,j);}
}
}
front = c[4][4];
int fu=front;
for(num=fu-1;num>0;num--)
{
for(i=4;i>=0;i--)
{
for(j=4;j>=0;j--)
{
if(c[i][j]==front-1&&c[i][j]!=0)
{
x.push(i);
y.push(j);
front=c[i][j];
}
}
}
}
while(!x.empty()&&!y.empty())
{
cout<<"("<<x.top()<<", "<<y.top()<<")\n";
x.pop();y.pop();
}
cout<<"("<<4<<", "<<4<<")\n";
return 0;
}