newcoder-迷宫问题

定义一个二维数组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)

代码:

#include<iostream>
#include<string.h>
#include<cstdio>
using namespace std;
int M, N;
#define  NUM 10
#define QSize 110
int map[NUM][NUM];

int go[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };//定义4个方向

struct node{
    int pos_x, pos_y, pre;
}queue[QSize];//设置一个50个格子的队列


int front = 0;
int rear = 0;//设置队头和队尾,头指针指向头元素,尾指针指向队尾的下一个位置
int vis[NUM][NUM];//为什么访问数组需要放在最后面???


//广度优先遍历
void bfs(int beginX, int beginY, int endX, int endY){
    queue[0].pos_x = beginX, queue[0].pos_y = beginY, queue[0].pre = -1;//将初始结点[0,0]压入队列
    rear = rear + 1;
    vis[beginX][beginY] = 1;
    while (front<rear){//如果队列不为空
        for (int i = 0; i<4; i++){//4个方向搜索可达的方向
            int newx = queue[front].pos_x + go[i][0];
            int newy = queue[front].pos_y + go[i][1];
            if (newx<0 || newx>M || newy<0 || newy>N || map[newx][newy] == 1 || vis[newx][newy] == 1)//是否在迷宫内,是否撞墙,是否已走过
                continue;
            //进队
            queue[rear].pos_x = newx;
            queue[rear].pos_y = newy;
            queue[rear].pre = front;
            rear++;
            vis[newx][newy] = 1;//给走过的位置做标记

            if (newx == endX-1&&newy == endY-1)
            {
                return;
            }
        }
        front++;//出队
    }
}



void output(node current){
    if (current.pre == -1)
        cout << "(" << current.pos_x << "," << current.pos_y << ")" << endl;
    else{
        output(queue[current.pre]);
        cout << "(" << current.pos_x << "," << current.pos_y << ")" << endl;
    }
}
int main()
{
    int i, j;
    while (cin >> M >> N)
    {
    memset(vis, 0, sizeof(vis));
    memset(map, 0, sizeof(map));
    for (i = 0; i < M; i++)
    {
        for (j = 0; j < N; j++)
        {
            cin >> map[i][j];
        }
    }
    front = 0;
    rear = 0;
    bfs(0, 0, M, N);
    output(queue[rear - 1]);
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/gcter/p/10403340.html