[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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值