[LeetCode] 79. Word Search 单词搜索
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
给定一个2维的字母board,判断 是否有一个网格路径组成给定的单词。
解法:DFS, 典型的深度优先遍历,对每一点的每一条路径进行深度遍历,遍历过程中一旦出现:
1.数组越界。2.该点已访问过。3.该点的字符和word对应的index字符不匹配。
就要对该路径进行剪枝:
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public boolean exist( char [][] board, String word) { int m = board.length; int n = board[ 0 ].length; boolean result = false ; for ( int i= 0 ; i<m; i++){ for ( int j= 0 ; j<n; j++){ if (dfs(board,word,i,j, 0 )){ result = true ; } } } return result; } public boolean dfs( char [][] board, String word, int i, int j, int k){ int m = board.length; int n = board[ 0 ].length; if (i< 0 || j< 0 || i>=m || j>=n){ return false ; } if (board[i][j] == word.charAt(k)){ char temp = board[i][j]; board[i][j]= '#' ; if (k==word.length()- 1 ){ return true ; } else if (dfs(board, word, i- 1 , j, k+ 1 ) ||dfs(board, word, i+ 1 , j, k+ 1 ) ||dfs(board, word, i, j- 1 , k+ 1 ) ||dfs(board, word, i, j+ 1 , k+ 1 )){ return true ; } board[i][j]=temp; } return false ; } |
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution { int [] dh = { 0 , 1 , 0 , - 1 }; int [] dw = { 1 , 0 , - 1 , 0 }; public boolean exist( char [][] board, String word) { boolean [][] isVisited = new boolean [board.length][board[ 0 ].length]; for ( int i = 0 ; i < board.length; i++) for ( int j = 0 ; j < board[ 0 ].length; j++) if (isThisWay(board, word, i, j, 0 , isVisited)) return true ; return false ; } public boolean isThisWay( char [][] board, String word, int row, int column, int index, boolean [][] isVisited) { if (row < 0 || row >= board.length || column < 0 || column >= board[ 0 ].length || isVisited[row][column] || board[row][column] != word.charAt(index)) return false ; //剪枝 if (++index == word.length()) return true ; //word所有字符均匹配上 isVisited[row][column] = true ; for ( int i = 0 ; i < 4 ; i++) if (isThisWay(board, word, row + dh[i], column + dw[i], index, isVisited)) return true ; //以board[row][column]为起点找到匹配上word路径 isVisited[row][column] = false ; //遍历过后,将该点还原为未访问过 return false ; } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Solution: # @param board, a list of lists of 1 length string # @param word, a string # @return a boolean def exist( self , board, word): visited = [[ False for j in xrange ( len (board[ 0 ]))] for i in xrange ( len (board))] for i in xrange ( len (board)): for j in xrange ( len (board[ 0 ])): if self .existRecu(board, word, 0 , i, j, visited): return True return False def existRecu( self , board, word, cur, i, j, visited): if cur = = len (word): return True if i < 0 or i > = len (board) or j < 0 or j > = len (board[ 0 ]) or visited[i][j] or board[i][j] ! = word[cur]: return False visited[i][j] = True result = self .existRecu(board, word, cur + 1 , i + 1 , j, visited) or \ self .existRecu(board, word, cur + 1 , i - 1 , j, visited) or \ self .existRecu(board, word, cur + 1 , i, j + 1 , visited) or \ self .existRecu(board, word, cur + 1 , i, j - 1 , visited) visited[i][j] = False return result |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution { public : bool exist(vector<vector< char > > &board, string word) { if (word.empty()) return true ; if (board.empty() || board[0].empty()) return false ; vector<vector< bool > > visited(board.size(), vector< bool >(board[0].size(), false )); for ( int i = 0; i < board.size(); ++i) { for ( int j = 0; j < board[i].size(); ++j) { if (search(board, word, 0, i, j, visited)) return true ; } } return false ; } bool search(vector<vector< char > > &board, string word, int idx, int i, int j, vector<vector< bool > > &visited) { if (idx == word.size()) return true ; if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || visited[i][j] || board[i][j] != word[idx]) return false ; visited[i][j] = true ; bool res = search(board, word, idx + 1, i - 1, j, visited) || search(board, word, idx + 1, i + 1, j, visited) || search(board, word, idx + 1, i, j - 1, visited) || search(board, word, idx + 1, i, j + 1, visited); visited[i][j] = false ; return res; } }; |
类似题目:
[LeetCode] 212. Word Search II 词语搜索 II
[LeetCode] 348. Design Tic-Tac-Toe 设计井字棋游戏
All LeetCode Questions List 题目汇总
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具