Leetcode - Word Search II
Leetcode - Largest Unique Number

Leetcode - Word Search

violet posted @ Mar 28, 2020 01:17:54 AM in 算法 with tags Algorithm DFS backtracking , 253 阅读

https://leetcode.com/problems/word-search/

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Use dfs to search in the board.

func exist(board [][]byte, word string) bool {
        for i := 0; i < len(board); i++ {
        for j := 0; j < len(board[0]); j++ {
            if dfs(board, []byte(word), i, j, 0) {
                return true
            }
        }
    }
    return false
}

func dfs(board [][]byte, word []byte, i, j, start int) bool {
    c := board[i][j]
    if c != word[start] {
        return false
    }
    if start == len(word)-1 {
        return true
    }
    directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
    //fmt.Println("c: ", string(c))


    board[i][j] = '#'
    var result bool
    for _, d := range directions {
        newx := i + d[0]
        newy := j + d[1]
        if newx >= 0 && newy >= 0 && newx < len(board) && newy < len(board[0]) && !result {
            result = dfs(board, word, newx, newy, start+1)
            //fmt.Println("result: ", result)
        }
    }
    board[i][j] = c
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter