HJ43 迷宫问题

题目描述

定义一个二维数组 N*M ,如 5 × 5 数组下所示:

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};


它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的路线。入口点为[0,0],既第一格是可以走的路。

数据范围: 2 \le n,m \le 10 \2n,m10  , 输入的内容只包含 0 \le val \le 1 \0val1 

输入描述:

输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。

输出描述:

左上角到右下角的最短路径,格式如样例所示。

示例

复制代码
输入:
5 5
0 1 0 0 0
0 1 1 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)
复制代码

 

解题思路:

 这里使用回溯法,也就是递归来实现路径记录。没啥好说的看代码。注:map不能是全局的。应该随每条路线变化。

代码如下:

复制代码
#include<iostream>
#include<vector>
#include<queue>
#include<string.h>

using namespace std;

struct Node {
    int x;
    int y;
};


vector<Node> res;
int xx[4] = { 0,0,-1,1 };
int yy[4] = { -1,1,0,0 };
int n, m;
void dfs(vector<vector<int>>& map, int x, int y, vector<Node> path) {
    Node node;
    node.x = x;
    node.y = y;
    path.push_back(node);
    map[x][y] = 1;
    if (x == n - 1 && y == m - 1) {
        res = path;
        return;
    }

    for (int i = 0; i < 4; i++) {
        if ( (node.x + xx[i]) >= 0 && (node.x + xx[i]) < n && (node.y + yy[i]) >= 0 && (node.y + yy[i]) < m ) {
            int tx = node.x + xx[i];
            int ty = node.y + yy[i];
            int flag = map[ node.x + xx[i] ][ node.y + yy[i]];
            if(!map[node.x + xx[i]][node.y + yy[i]])
                bfs(map, node.x + xx[i], node.y + yy[i], path);
        }
    }
    path.pop_back();
    map[x][y] = 0;
    return;
}

int main() {
    while (cin >> n >> m) {
        vector<vector<int> > map(n, vector<int>(m, 0));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cin >> map[i][j];
            }
        }
        vector<Node> path;
        dfs(map, 0, 0, path);
        for (vector<Node>::iterator ite = res.begin(); ite < res.end(); ite++) {
            cout << "(" << ite->x << "," << ite->y << ")" << endl;
        }
    }
}
复制代码

 

 

posted @   An2i  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2018-08-05 XML学习
点击右上角即可分享
微信分享提示