定義一個二維數組:
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表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。
Input
一個5 × 5的二維數組,表示一個迷宮。數據保證有唯一解。
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)
#include <iostream>
using namespace std;
int m = 99;
int a[5][5];
int b[5][5] = {1, 0 };
int c[5][5] = {0};
void dfs(int x, int y, int step)
{
if ( x == 4 && y == 4)
{
if (step < m)
{
m = step;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
{
c[i][j] = b[i][j];///記錄迷宮的座標
}
}
return;
}
int next[4][2]=
{
{-1,0} ,{1,0} ,{0,-1},{0,1} //上下左右
};
for (int k = 0; k < 4; k++)
{
int nx, ny;
nx = x + next[k][0];
ny = y + next[k][1];
if (nx < 0 || nx>5 || ny < 0 || ny>5)continue;
if (a[nx][ny] == 0 && b[nx][ny] == 0)
{
b[nx][ny] = 1;
dfs(nx, ny, step + 1);
b[nx][ny] = 0;
}
}
return;
}
int main()
{
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
cin >> a[i][j];
dfs(0, 0, 0);
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
{
if (c[i][j] == 1)
cout << "(" << i << ", " << j << ")" << endl;
}
}