Skip to content

Latest commit

 

History

History
110 lines (73 loc) · 2.75 KB

79.Word-Search.md

File metadata and controls

110 lines (73 loc) · 2.75 KB

79. Word Search

題目


Given an m x n grid of characters board and a string word, return true if word exists in the grid.

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

Example 1:

https://assets.leetcode.com/uploads/2020/11/04/word2.jpg

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

https://assets.leetcode.com/uploads/2020/10/15/word3.jpg

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

思路


Code


  • GoLang

    Runtime 375ms **Beats 25.83%**of users with Go

    Memory 2.11MB **Beats 26.82%**of users with Go

    func exist(board [][]byte, word string) bool {
        rows, cols := len(board), len(board[0])
        visited := make(map[int]bool)
        var backtracking func(row, col int, target string) bool
        backtracking = func(row, col int, target string) bool {
            if row < 0 || row >= rows ||
               col < 0 || col >= cols ||
               visited[row*cols + col] ||
               target[0] != board[row][col]  {
                   return false
            }
    
            target = target[1:len(target)]
            visited[row*cols + col] = true
    
            if target == "" {
                return true
            }
    
            isExisted := backtracking(row + 1, col, target) ||
                backtracking(row - 1, col, target) ||
                backtracking(row, col + 1, target) ||
                backtracking(row, col - 1, target)
    
            visited[row*cols + col] = false
    
            return isExisted
        }
    
        for r := 0; r < rows; r++ {
            for c := 0; c < cols; c++ {
                if backtracking(r, c, word) {
                    return true
                }
            }
        }
    
        return false
    }

Reference