题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

package main

import (
    "fmt"
)

func dfs(matrix [][]int, row int, col int, visited [][]bool, path *[][2]int) bool {
    m, n := len(matrix), len(matrix[0])

    // 递归出口
    if row == m-1 && col == n-1 {
        *path = append(*path, [2]int{row, col})
        return true
    }

    if row<0 || row>=m || col<0 || col>=n || matrix[row][col] == 1 || visited[row][col] {
        return false
    }

    *path = append(*path, [2]int{row, col})
    visited[row][col] = true

    if dfs(matrix, row-1, col, visited, path) || dfs(matrix, row+1, col, visited, path) || dfs(matrix, row, col-1, visited, path) || dfs(matrix, row, col+1, visited, path) {
        return true
    }

    *path = (*path)[:len(*path)-1]
    visited[row][col] = false
    return false
}

func main() {
    var m, n int
    fmt.Scan(&m, &n)

    matrix := make([][]int, m)
    for i:=0; i<m; i++ {
        matrix[i] = make([]int, n)
    }

    for i:=0; i<m; i++ {
        for j:=0; j<n; j++ {
            var num int
            fmt.Scan(&num)
            matrix[i][j] = num
        }
    }

    visited := make([][]bool, m)
    for i:=0; i<m; i++ {
        visited[i] = make([]bool, n)
    }
    var path [][2]int
    dfs(matrix, 0, 0, visited, &path)

    for _, p := range path {
        fmt.Printf("(%d,%d)\n", p[0], p[1])
    }
}
// 本题输入为一个矩阵,所以采用 fmt.Scan(&m, &n)

全部评论

相关推荐

09-29 11:19
门头沟学院 Java
点赞 评论 收藏
分享
把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务