Leetcode 79. 单词搜索 (每日一题 20210720 同类型题)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 79. 单词搜索 (每日一题 20210720 同类型题)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)?m x n 二維字符網(wǎng)格?board 和一個(gè)字符串單詞?word 。如果?word 存在于網(wǎng)格中,返回 true ;否則,返回 false 。單詞必須按照字母順序,通過(guò)相鄰的單元格內(nèi)的字母構(gòu)成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個(gè)單元格內(nèi)的字母不允許被重復(fù)使用。示例 1:輸入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
輸出:true
示例 2:輸入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
輸出:true
示例 3:輸入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
輸出:false提示:m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 僅由大小寫(xiě)英文字母組成鏈接:https://leetcode-cn.com/problems/word-searchclass Solution:def exist(self, board: List[List[str]], word: str) -> bool:row, col = len(board), len(board[0])def dfs(x, y, index):if board[x][y] != word[index]:return Falseif index == len(word) - 1:return Trueboard[x][y] = '#'for c in [[0,1],[0,-1],[-1,0],[1,0]]:nx, ny = x + c[0], y + c[1]if 0 <= nx < row and 0 <= ny < col and dfs(nx, ny, index+1):return Trueboard[x][y] = word[index]for i in range(row):for j in range(col):if dfs(i,j,0):return Truereturn False
總結(jié)
以上是生活随笔為你收集整理的Leetcode 79. 单词搜索 (每日一题 20210720 同类型题)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Leetcode 200 岛屿数量 (每
- 下一篇: Leetcode 130. 被围绕的区域