1:迷宫问题
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
输入
一个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)
代码有注释,自己看吧。
#include <iostream>
int step[4][2] = {-1,0,0,-1,1,0,0,1};
int visited[10][10];
using namespace std;
struct node{
int r,c;
int f;//表示父节点的位置;
};
//对于该node 创建一个30的数组,因为总共也就25个,所以是符合的;
template <class T>
class myQueue {
private:
int length;
T queue[30]; //建立一个数组
int front;
int rear;
public:
myQueue(); //构造函数
bool isEmpty() const{return front == rear;}
void Push(const T x);
void Pop();
int getFrontNumber();
T getFront();
T getNumber(int number);
};
template<class T>
myQueue<T>::myQueue(){
front = 0;
rear = 0;
}
template<class T>
void myQueue<T>::Push(const T x){
queue[rear] = x;
rear++;
}
template<class T>
void myQueue<T>::Pop(){
front ++;
}
template<class T>
T myQueue<T>::getFront(){
return queue[front];
}
template<class T>
int myQueue<T>::getFrontNumber(){
return front;
}
template<class T>
T myQueue<T>::getNumber(int number){
return queue[number];
}
int main() {
int map[10][10];
int num = 1;
for(int i = 1; i <= 5; i++){
for(int j = 1; j <= 5; j++){
cin >> map[i][j];
}
}
//初始化
visited[1][1] = 1;
myQueue<node> q;
node* aa = new node[30]; //先定一个存储node的数组;
aa[0] = {1,1,-1};
q.Push(aa[0]);
node tmp1,tmp2;
int nowr,nowc,nowf;
// BFS 入队列
while(!q.isEmpty())
{
tmp1 = q.getFront();
nowf = q.getFrontNumber();
q.Pop();
nowr = tmp1.r;
nowc = tmp1.c;
for(int i = 0; i <=3; i++)
{
int rr = nowr + step[i][0];
int cc = nowc + step[i][1];
if(rr >0 && rr <= 5 && cc > 0 && cc <= 5 && !visited[rr][cc] && map[rr][cc] == 0)
{
visited[rr][cc] = 1;
num++;
aa[num] = {rr, cc, nowf};
q.Push(aa[num]);
}
}
}
//先找到,再逆序输出;
int number = q.getFrontNumber();
int count = 0;
int total = 0;
node *bb = new node[30]; //用bb来存储输出
number --;
while(true){
tmp2 = q.getNumber(number);
nowf = tmp2.f;
nowr = tmp2.r;
nowc = tmp2.c;
bb[count++] = {nowr-1, nowc-1,nowf};
total = count;
number = nowf;
if(nowf == -1)
break;
}
//逆序输出
for(int i = total-1; i>=0; i--)
cout << "(" << bb[i].r << ", " << bb[i].c << ")" << endl;
return 0;
}