您的位置:首页 > 教育 > 培训 > 厦门百度seo_石家庄建设信息网_抖音流量推广神器软件_厦门百度代理

厦门百度seo_石家庄建设信息网_抖音流量推广神器软件_厦门百度代理

2025/9/20 9:30:29 来源:https://blog.csdn.net/ShadyPi/article/details/143065722  浏览:    关键词:厦门百度seo_石家庄建设信息网_抖音流量推广神器软件_厦门百度代理
厦门百度seo_石家庄建设信息网_抖音流量推广神器软件_厦门百度代理

Search for Word

Given a 2-D grid of characters board and a string word, return true if the word is present in the grid, otherwise return false.

For the word to be present it must be possible to form it with a path in the board with horizontally or vertically neighboring cells. The same cell may not be used more than once in a word.

Example 1:

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

Example 2:

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

Constraints:

1 <= board.length, board[i].length <= 5
1 <= word.length <= 10

board and word consists of only lowercase and uppercase English letters.

Solution

DFS and BFS are all appliable for this problem but pay attention to the constraints that each cell can only be used once. So, we need an additional 2-D array to record the cells we have passed.

Code

class Solution:def exist(self, board: List[List[str]], word: str) -> bool:dir_x = [-1, 1, 0, 0]dir_y = [ 0, 0,-1, 1]vis = [[0]*len(board[0]) for _ in range(len(board))]def dfs(x, y, pos):if board[x][y] != word[pos]:return Falseif pos == len(word)-1:return Truevis[x][y] = 1for i in range(len(dir_x)):nxt_x = x+dir_x[i]nxt_y = y+dir_y[i]if 0 <= nxt_x < len(board) and 0 <= nxt_y < len(board[0]) and vis[nxt_x][nxt_y]==0:if dfs(nxt_x, nxt_y, pos+1):return Truevis[x][y] = 0return Falsefor i in range(len(board)):for j in range(len(board[0])):if dfs(i, j, 0):return Truereturn False

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com