[LeetCode]Word Search
来源:互联网 发布:js.寄存器属性 编辑:程序博客网 时间:2024/06/14 23:15
Question
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.
本题难度Medium。
DFS
【复杂度】
时间 O(MN) 空间 O(1)
【思路】
对矩阵里每个点都进行一次深度优先搜索,看它能够产生一个路径和所给的字符串是一样的。要注意题目的要求:The same letter cell may not be used more than once. 这就需要对本路径上已经搜索过的元素进行标记,等递归回来再变回原值。
【注意】
26-36行不要写成:
for(int i=-1;i<=1;i=i+1){ for(int j=-1;j<=1;j=j+1){ if(helper(x+i,y+j,index+1,board,word)) return true; } }}
我们举例说明为什么不能这样。对于:
1 2 34 X 56 7 8
本该只搜索2 4 5 7
,如果按上面代码,就会搜索1 3 6 8
【代码】
public class Solution { int m=0; int n=0; public boolean exist(char[][] board, String word) { //require m=board.length; if(m<1) return false; n=board[0].length; //invariant for(int i=0;i<m;i++) for(int j=0;j<n;j++) if(helper(i,j,0,board,word)) return true; //ensure return false; } private boolean helper(int x,int y,int index,char[][] board, String word){ //base case if(index==word.length()) return true; if(isValid(x,y)&&board[x][y]==word.charAt(index)){ char tmp=board[x][y]; board[x][y]='\0'; //标记 for(int i=-1;i<=1;i=i+1){ if(i==0){ for(int j=-1;j<=1;j=j+1){ if(helper(x+i,y+j,index+1,board,word)) return true; } }else{ if(helper(x+i,y,index+1,board,word)) return true; } } board[x][y]=tmp; //再变回来 } return false; } private boolean isValid(int x,int y){ if(0<=x&&x<m&&0<=y&&y<n) return true; return false; }}
【附】
我曾经想优化上面的代码,办法是对搜索过的区域进行“永久性”标记,即使递归也不还原。但是对于下面的例子就不行:
a b c dq q c qq q c qa b c qword="abccccd"
这样得到的结果是false。
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- 解决CentOS7虚拟机无法上网并设置CentOS7虚拟机使用静态IP上网
- java 基础
- Nutch简介及安装(转载)
- Trafodion 查看执行计划
- hover 时图片旋转
- [LeetCode]Word Search
- 负载均衡 LB(Load Balance)-- 方案评估
- C语言思考题
- AsyncTask的源码解析及遇到的一些问题
- c语言 输出最新的错误信息
- 切换fragment时报not attached to Activity错误
- Android通过包名或类名启动APP或者一个Activity 以及 判断APP的运行状态
- aapt命令的使用
- Android Studio导入开源项目的正确姿势