LeetCode 单词搜索
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | class Solution { public : bool flag= false ; bool dfs(vector<vector< char >>& board, string &word, int rindex, int sindex, int cindex){ if (rindex>=board.size()||rindex<0||cindex>=board[rindex].size()||cindex<0||board[rindex][cindex]!=word[sindex]){ return false ; } if (sindex==word.size()-1&&board[rindex][cindex]==word[sindex]){ return true ; } board[rindex][cindex]= '.' ; flag= (dfs(board,word,rindex-1,sindex+1,cindex)|| dfs(board,word,rindex+1,sindex+1,cindex)|| dfs(board,word,rindex,sindex+1,cindex-1)|| dfs(board,word,rindex,sindex+1,cindex+1)); board[rindex][cindex]=word[sindex]; return flag; } bool exist(vector<vector< char >>& board, string word) { for ( int i=0;i<board.size();i++){ for ( int j=0;j<board[i].size();j++){ if (dfs(board,word,i,0,j)){ return true ; }; } } return false ; } };<br><br><br>第二段(超出时间限制): class Solution { public : bool flag= false ; void dfs(vector<vector< char >>& board, string &word, int rindex, int sindex, int cindex){ if (rindex>=board.size()||rindex<0||cindex>=board[rindex].size()||cindex<0||board[rindex][cindex]!=word[sindex]){ return ; } if (sindex==word.size()-1&&board[rindex][cindex]==word[sindex]){ flag= true ; return ; } board[rindex][cindex]= '.' ; dfs(board,word,rindex-1,sindex+1,cindex); dfs(board,word,rindex+1,sindex+1,cindex); dfs(board,word,rindex,sindex+1,cindex-1); dfs(board,word,rindex,sindex+1,cindex+1); board[rindex][cindex]=word[sindex]; } bool exist(vector<vector< char >>& board, string word) { for ( int i=0;i<board.size();i++){ for ( int j=0;j<board[i].size();j++){ if (flag== true ){ return true ; } dfs(board,word,i,0,j); } } return flag; } }; |
两端差别是dfs四个方向(上下左右),第二段代码需要上下左右全部进行遍历,但是由于有时候在向上进行遍历的时候就已经满足条件,所以此时用或更好,因为在向上满足条件时就不对剩下的进行dfs,减少了时间
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!