首页 > 试题广场 >

迷宫问题

[编程题]迷宫问题
  • 热度指数:196706 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

定义一个二维数组 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],既第一格是可以走的路。


数据范围: , 输入的内容只包含


输入描述:

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



输出描述:

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

示例1

输入

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)
示例2

输入

5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 1
0 1 1 1 0
0 0 0 0 0

输出

(0,0)
(1,0)
(2,0)
(3,0)
(4,0)
(4,1)
(4,2)
(4,3)
(4,4)

说明

注意:不能斜着走!!     
const rl = require("readline").createInterface({ input: process.stdin });
const iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    const [N, M] = (await readline()).split(" ").map(Number);
    const matrix = [];
    let i = 0;
    while (i++ < N) {
        matrix.push((await readline()).split(" ").map(Number));
    }

    const [x, y] = [0, 0];
    let res = null;

    const recursion = (i, j, previousDirection, prevPath) => {
        if (res !== null) return;
        if (i < 0 || i >= N || j < 0 || j >= M) return;

        const path = [...prevPath];
        path.push(`(${i},${j})`);

        if (i === N - 1 && j === M - 1) return (res = path);

        // UP
        if (
            previousDirection !== "DOWN" &&
            i - 1 >= 0 &&
            matrix[i - 1][j] !== 1
        ) {
            recursion(i - 1, j, "UP", path);
        }
        // RIGHT
        if (
            previousDirection !== "LEFT" &&
            j + 1 < M &&
            matrix[i][j + 1] !== 1
        ) {
            recursion(i, j + 1, "RIGHT", path);
        }
        // DOWN
        if (previousDirection !== "UP" && i + 1 < N && matrix[i + 1][j] !== 1) {
            recursion(i + 1, j, "DOWN", path);
        }
        // LEFT
        if (
            previousDirection !== "RIGHT" &&
            j - 1 >= 0 &&
            matrix[i][j - 1] !== 1
        ) {
            recursion(i, j - 1, "LEFT", path);
        }
        return;
    };

    recursion(x, y, undefined, []);

    res.map((r) => console.log(r));
})();

编辑于 2024-02-26 14:31:30 回复(0)
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var flag=true,m,n,arr=[],res
function findWay(i,j,direction,path){
    if(i==m-1 && j==n-1){
        for(let i in path){
            console.log('('+path[i][0]+','+path[i][1]+')')
        }
    }
    if(i+1<m && arr[i+1][j]==0 && direction[1]!=0){
        findWay(i+1,j,[0,1,1,1],path.concat([[i+1,j]]))
    }
    if(i-1>=0 && arr[i-1][j]==0 && direction[0]!=0){
        findWay(i-1,j,[1,0,1,1],path.concat([[i-1,j]]))
    }
    if(j+1<n && arr[i][j+1]==0 && direction[3]!=0){
        findWay(i,j+1,[1,1,0,1],path.concat([[i,j+1]]))
    }
    if(j-1>=0 && arr[i][j-1]==0 && direction[2]!=0){
        findWay(i,j-1,[1,1,1,0],path.concat([[i,j-1]]))
    }
}
rl.on('line', function (line) {
    const tokens = line.split(' ');
    if (tokens[tokens.length-1]=='') tokens.pop()
    if(flag){
        m=parseInt(tokens[0]),n=parseInt(tokens[1])
        flag=false
    }
    else{
        arr.push(tokens.map((value,index,arr)=>{
            return parseInt(value)
        }))
        if(arr.length==m){
            //console.log(arr)
            findWay(0,0,[0,1,0,1],[[0,0]])
            arr=[]
            flag=true
        }
    }
});
js递归
发表于 2021-09-27 19:12:36 回复(0)

Node环境的解法来一个 思路和其他语言的差不多

const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
let N = 0
let M = 0
let arr = []
let Maze = []
let MazeResult = []
let count = 0
rl.on('line', line => {
  arr.push(line)
  if(arr.length == 1) {
    N = Number(arr[0].split(' ')[0])
    M = Number(arr[0].split(' ')[1])
  }
  if(arr.length == N+1) {
    Maze = arr.slice(1)
    Maze = Maze.map(item => {
       temp = item.split(' ')
      return temp
    })
    handleMaze(0, 0)
    MazeResult.forEach(item => {
      console.log(`(${item.row},${item.col})`)
    })
    N = 0
    M = 0
    arr = []
    Maze = []
    MazeResult = []
  }
})
 function handleMaze(row, col) {
    if (Maze[row][col] == 0) {
      MazeResult.push({row: row, col: col})
    }
    Maze[row][col] = 1
    if (row === N-1 && col === M-1) return
    if (col+1<M && Maze[row][col+1] == 0) { //right
      handleMaze(row, col+1)
    } else if (row+1<N && Maze[row+1][col] == 0) { //bottom
      handleMaze(row+1, col)
    } else if (col>=1&&Maze[row][col-1] == 0) { //left
      handleMaze(row, col-1)
    } else if (row>=1 && Maze[row-1][col] == 0) { //top
      handleMaze(row-1, col)
    } else { //noway
      MazeResult.pop()
      let pre = MazeResult.slice(-1)[0]
      handleMaze(pre.row, pre.col)
    }
  }
编辑于 2021-06-29 17:45:58 回复(0)

问题信息

难度:
3条回答 100336浏览

热门推荐

通过挑战的用户

查看代码