二维字符矩阵搜索单词

64 阅读1分钟

Given a rectangular matrix of English lowercase letters board and a string word, your task is to find the number of occurrences of word in the rows(), columns() and diagonals() of board.

For Example

eg1
board = [['s', 'o', 's', 'o'],
         ['s', 'o', 'o', 's'],
         ['s', 's', 's', 's']]
and word = "sos", 
the output should be solution(board, word) = 3.

There are 2 occurrences of word starting from board[0][0](going → and ↘), and one starting from board[0][2](going ↓).

No other occurrences of word were counted, so the answer is 3.

eg2
board = [['a', 'a'],
         ['a', 'a']]
and word = "aa", the output should be
solution(board, word) = 5.

There are 2 horizontal, 2, vertical, and 1 diagonal occurrence of word, for a total of 5.

implement this function

func solution(board [][]string, word string) int {}

解法一:模拟法

func solution11(board [][]string, word string) int {
    rows := len(board)
    if rows == 0 {
       return 0
    }
    cols := len(board[0])
    res := 0

    // 遍历矩阵的每一个元素
    for i := 0; i < rows; i++ {
       for j := 0; j < cols; j++ {
          // 检查行方向
          if j+len(word) <= cols {
             match := true
             for idx := 0; idx < len(word); idx++ {
                if board[i][j+idx] != string(word[idx]) {
                   match = false
                   break
                }
             }
             if match {
                res++
             }
          }

          // 检查列方向
          if i+len(word) <= rows {
             match := true
             for idx := 0; idx < len(word); idx++ {
                if board[i+idx][j] != string(word[idx]) {
                   match = false
                   break
                }
             }
             if match {
                res++
             }
          }

          // 检查对角线方向
          if i+len(word) <= rows && j+len(word) <= cols {
             match := true
             for idx := 0; idx < len(word); idx++ {
                if board[i+idx][j+idx] != string(word[idx]) {
                   match = false
                   break
                }
             }
             if match {
                res++
             }
          }
       }
    }
    return res
}