0
点赞
收藏
分享

微信扫一扫

[LeetCode]Word Search


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 3
4 X 5
6 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 d
q q c q
q q c q
a b c q
word="abccccd"

这样得到的结果是false。


举报

相关推荐

0 条评论