迷宫最短路问题

题意:从迷宫左上角到左下角,求最短路

输入:迷宫的横纵坐标和迷宫元素

输出:迷宫最短路所经过的坐标

代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <string>

using namespace std;

int dx[] = {1,1,0,-1,-1,-1,0,1};
int dy[] = {0,-1,-1,-1,0,1,1,1};
int n, m;
int ** maze;
bool ** vis;

struct node
{
    int x, y;
    string  record;
    node(int a, int b,string s):x(a),y(b)
    {
        record = s;
    }
    node()
    {
        x = y = 0;
    }
};
queue<node> qu;
string BFS()
{
    node cur;
    string nex;
    int c,r;
    //记录路径
    cur.x = 1,cur.y = 1;
    cur.record = "(1,1)\n";
    qu.push(cur);
    vis[1][1] = 1;
    while(!qu.empty())
    {
        cur = qu.front();
        qu.pop();
        //判断是否已经达到终点
        if(cur.x == n && cur.y == m)
        {
            return cur.record;
        }
        for(int i = 0 ; i < 8; i++)
        {
            //方向调整
            r = cur.x + dx[i];
            c = cur.y + dy[i];
            if(r >= 1 && r <= n && c >= 1 && c <= m
                    && vis[r][c] == 0 && maze[r][c] == 0)
            {
                vis[r][c] = 1;
                nex = cur.record;
                nex += "(";
                nex += (char)('0'+r);
                nex += ",";
                nex += (char)('0'+c);
                nex += ")\n";
                qu.push(node(r,c,nex));
            }
        }
    }
}

void print()
{
    for(int i = 0; i < n + 2; i++)
    {
        for(int j = 0 ; j < m + 2; j++)
        {
            cout << maze[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    for(int i = 0 ; i < n+2; i++)
    {
        for(int j = 0 ; j < m+2; j++)
        {
            cout << vis[i][j] << " ";
        }
        cout << endl;
    }
    return;
}

int main()
{
    freopen("in.txt","r",stdin);
    cin >> n >> m;
    maze = new int* [n+2];
    vis = new bool* [n+2];
    for(int i = 0 ; i < n + 2; i++)
    {
        maze[i] = new int[m+2];
        vis[i] = new bool[m+2];
    }
    for(int i = 0 ; i < n+2; i++)
    {
        for(int j = 0 ; j < m+2; j++)
        {
            maze[i][j] = 1;
            vis[i][j] = 1;
        }
    }
    for(int i = 1; i <= n ; i++)
        for(int j = 1; j <= m ; j++)
        {
            cin >> maze[i][j];
            vis[i][j] = 0;
        }
//    print();
    string tmp = BFS();
    cout << tmp << endl;

    return 0;
}

代码改变世界