class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
}
};
面试题12. 矩阵中的路径
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd" 输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
和 word
仅由大小写英文字母组成注意:本题与主站 79 题相同:https://leetcode.cn/problems/word-search/
原站题解
golang 解法, 执行用时: 120 ms, 内存消耗: 1.9 MB, 提交时间: 2022-11-14 11:13:40
type pair struct{ x, y int } var directions = []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} // 上下左右 func exist(board [][]byte, word string) bool { h, w := len(board), len(board[0]) vis := make([][]bool, h) for i := range vis { vis[i] = make([]bool, w) } var check func(i, j, k int) bool check = func(i, j, k int) bool { if board[i][j] != word[k] { // 剪枝:当前字符不匹配 return false } if k == len(word)-1 { // 单词存在于网格中 return true } vis[i][j] = true defer func() { vis[i][j] = false }() // 回溯时还原已访问的单元格 for _, dir := range directions { if newI, newJ := i+dir.x, j+dir.y; 0 <= newI && newI < h && 0 <= newJ && newJ < w && !vis[newI][newJ] { if check(newI, newJ, k+1) { return true } } } return false } for i, row := range board { for j := range row { if check(i, j, 0) { return true } } } return false }
python3 解法, 执行用时: 5220 ms, 内存消耗: 15.1 MB, 提交时间: 2022-11-14 11:13:17
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def check(i: int, j: int, k: int) -> bool: if board[i][j] != word[k]: return False if k == len(word) - 1: return True visited.add((i, j)) result = False for di, dj in directions: newi, newj = i + di, j + dj if 0 <= newi < len(board) and 0 <= newj < len(board[0]): if (newi, newj) not in visited: if check(newi, newj, k + 1): result = True break visited.remove((i, j)) return result h, w = len(board), len(board[0]) visited = set() for i in range(h): for j in range(w): if check(i, j, 0): return True return False