Skip to content

Latest commit

 

History

History
39 lines (34 loc) · 957 Bytes

12. 矩阵中的路径.md

File metadata and controls

39 lines (34 loc) · 957 Bytes

解题思路

外层以矩阵中每个点作为起始位置进行查找,内层 dfs 查找时进行比较,看能否找全字符串

func exist(board [][]byte, word string) bool {
    for x := range board {
        for y := range board[x] {
            if dfs(board, word, x, y, 0) {
                return true
            }
        }
    }
    return false
}

func dfs(board [][]byte, word string, x, y, idx int) bool {
    if len(word) == idx {
        return true
    }
    if x < 0 || x >= len(board) || y < 0 || y >= len(board[0]) || word[idx] != board[x][y] {
        return false
    }
    // 标记被使用
    tmp := board[x][y]
    board[x][y] = '0'
    defer func() {
        board[x][y] = tmp
    }()
    return dfs(board, word, x+1, y, idx+1) ||
           dfs(board, word, x-1, y, idx+1) ||
           dfs(board, word, x, y+1, idx+1) ||
           dfs(board, word, x, y-1, idx+1)
}