定义一个二维数组:
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
第一行输入为测试用例的数目T。
接着是T个5× 5的二维数组,每个表示一个迷宫。
Output
左上角到右下角的最短路径的长度;如果不能通路,输出-1。格式如样例所示。
Sample Input
2
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
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 1
0 0 0 1 0
Sample Output
8
-1
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
int maze[5][5];
int dir[4][2] = { -1, 0, 1, 0, 0, 1, 0, -1 };
int visited[5][5];
struct point
{
int x;
int y;
};
queue<point>q;
point pre[5][5];
int dist[5][5];
int lateset_dir[5][5];
stack<point>out_path;
stack<int>out_dir;
bool FindShortestPath(point begin,point end)
{
q.push(begin);
while (!q.empty())
{
point curr = q.front();
q.pop();
visited[begin.x][begin.y] = 1;
for (int i = 0; i < 4; i++)
{
if (curr.x + dir[i][0] == 4 && curr.y + dir[i][1] == 4)
{
pre[4][4] = curr;
dist[4][4] = dist[curr.x][curr.y] + 1;
lateset_dir[4][4] = i;
return true;
}
int nx = curr.x + dir[i][0];
int ny = curr.y + dir[i][1];
if (nx >= 0 && nx <= 4 && ny >= 0 && ny <= 4 && visited[nx][ny] == 0 && maze[nx][ny] == 0)
{
visited[nx][ny] = 1;
point next;
next.x = nx;
next.y = ny;
q.push(next);
pre[nx][ny] = curr;
dist[nx][ny] = dist[curr.x][curr.y] + 1;
lateset_dir[nx][ny] = i;
}
}
}
return false;
}
void print_path(point p)
{
point tmp = pre[p.x][p.y];
if (tmp.x != p.x || tmp.y != p.y)//结束条件
{
out_path.push(p);
out_dir.push(lateset_dir[p.x][p.y]);
print_path(tmp);
}
}
void getPath(point p)
{
point tmp = pre[p.x][p.y];
while (1)
{
if (tmp.x == p.x && tmp.y == p.y)
{
break;
}
out_path.push(p);
out_dir.push(lateset_dir[p.x][p.y]);
p = tmp;
tmp = pre[tmp.x][tmp.y];
}
}
int main()
{
freopen("sample_input.txt", "r", stdin);
int test_case;
cin >> test_case;
for (int t = 0; t < test_case; t++)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
cin >> maze[i][j];
}
}
memset(visited, 0, sizeof(visited));
//清空队列为了第二次输入的maze
while (!q.empty())
{
q.pop();
}
point begin, end;
begin.x = 0; begin.y = 0;
end.x = 4; end.y = 4;
bool flag = FindShortestPath(begin, end);
if (flag)
{
cout << "Yes" << endl;
//print_path(end);
getPath(end);
while (!out_path.empty())
{
point tmp = out_path.top();
out_path.pop();
cout << tmp.x << " " << tmp.y << " " << endl;
}
while (!out_dir.empty())
{
int tmp = out_dir.top();
out_dir.pop();
if (tmp == 0)
cout << "Up " << endl;
else if (tmp == 1)
cout << "Down " << endl;
else if (tmp == 2)
cout << "Right " << endl;
else
cout << "Left " << endl;
}
}
else
{
cout << "No" << endl;
}
}
}