迷宫最短路问题

迷宫最短路问题

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

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

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

代码如下:
#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;
}

转载于:https://www.cnblogs.com/pprp/p/7653092.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值