题目描述
定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一空格是可以走的路。
Input
一个N × M的二维数组,表示一个迷宫。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
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)
输入描述:
输入两个整数,分别表示二位数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
输出描述:
左上角到右下角的最短路径,格式如样例所示。
输入例子:
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
输出例子:
(0,0) (1,0) (2,0) (2,1) (2,2) (2,3) (2,4) (3,4) (4,4)
一、深度搜索 思路:从起点位置开始,利用四个偏移量分别表示向右、向下、向左、向上移动;为了不走已经走过的位置,在走过的位置设置障碍物即设置该位置=1(采用双端队列,为了方便输出以及搜索过程)
#include<iostream>
#include<deque>
using namespace std;
struct pos
{
int x;
int y;
};
int main()
{
int n, m;
while (cin>>n>>m)
{
int **a = new int*[n];
for (int i = 0; i < n; i++)
a[i] = new int[m];
for (int i = 0; i < n;i++)
for (int j = 0; j < m; j++)
cin >> a[i][j];
deque<pos> s;
pos offset[4];//位置偏移
offset[0].x = 0; offset[0].y = 1;//向右
offset[1].x = 1; offset[1].y = 0;//向下
offset[2].x = 0; offset[2].y = -1;//向左
offset[3].x = -1; offset[3].y = 0;//向上
pos here;
here.x = 0;
here.y = 0;
s.push_back(here);
s.push_back(here);
int k ;
bool flag = false;//是否搜索完毕的标志符
while (!flag)
{ //如果没有找到,则返回上一个位置
here = s.back();
s.pop_back();
for (k = 0; k < 4;k++)
{ //4个方向的搜索
int r = here.x + offset[k].x;
int c = here.y + offset[k].y;
if (r == n - 1 && c == m - 1)
{ //找到出口则 将出口放入队列 并设置标识符及跳出循环
flag = true;
pos fin;
fin.x = n - 1;
fin.y = m - 1;
s.push_back(fin);
break;
}
if (r>=0&&r<=n-1&&c>=0&&c<=m-1&&a[r][c]==0)
{//如果当前位置为0且在搜索范围,则移动到当前位置,再接着搜索4个方向
pos next;
next.x = r; next.y = c;
a[r][c]=1;//设置为1,防止重复访问
s.push_back(next);
here = next;
k = -1;//记得将K设置为-1
}
}
}
while (!s.empty())//输出所走路径
{
cout << '('<<s.front().x << ',' << s.front().y<<')'<< endl;
s.pop_front();
}
}
return 0;
}
二、广度优先遍历,方法类似只不过偏移量设置为2个 向右和向下其他一致
#include<iostream>
#include<deque>
using namespace std;
struct pos
{
int x;
int y;
};
int main()
{
int n, m;
while (cin>>n>>m)
{
int **a = new int*[n];
for (int i = 0; i < n; i++)
a[i] = new int[m];
for (int i = 0; i < n;i++)
for (int j = 0; j < m; j++)
cin >> a[i][j];
deque<pos> s;
pos offset[2];
offset[0].x = 0; offset[0].y = 1; //向右
offset[1].x = 1; offset[1].y = 0; //向下
pos here;
here.x = 0;
here.y = 0;
s.push_back(here);
s.push_back(here);
int k ;
bool flag = false;
while (!flag)
{
here = s.back();
s.pop_back();
for (k = 0; k < 2;k++)
{
int r = here.x + offset[k].x;
int c = here.y + offset[k].y;
if (r == n - 1 && c == m - 1)
{
pos fin;
fin.x = n - 1;
fin.y = m - 1;
s.push_back(fin);
flag = true;
break;
}
if (r>=0&&r<=n-1&&c>=0&&c<=m-1&&a[r][c]==0)
{
pos next;
next.x = r; next.y = c;
a[r][c]=1;
s.push_back(next);
here = next;
k = -1;
}
}
}
while (!s.empty())
{
cout << '('<<s.front().x << ',' << s.front().y<<')'<< endl;
s.pop_front();
}
}
return 0;
}