LeetCode ! 79. Word search

参考资料:左程云算法课
79. Word Search
Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

Input: board =
[[“A”,“B”,“C”,“E”],
[“S”,“F”,“C”,“S”],
[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true

思路:主函数中枚举路径的起点board[i][j],从str[0]开始匹配str。只有有一个成功,就返回true.
设计递归函数检查从board[i][j]开始能够配出str[index…]。
注意:为了防止”走重复路“,应该给走过的点做上标记,尝试完四个方向之后记得恢复现场。(深度优先遍历)

“走重复路”的例子
board =
A B
D C
A
str = “ABCDA”
如果不给最左上角的A做上标记,那么等走到D时,有可能再次回到 最左上角的A, 即 “走重复路”,不符合题意。

 public  boolean exist(char[][] board, String s)
    {
        int n=  board.length;
        int m = board[0].length;
        char[] str = s.toCharArray();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(f(board,i,j,str,0))
                {
                    return true;
                }
            }
        }
        return false;

            // f(i,j,board,str,index) // start from [i][j] to match str[index..]
    }
    public boolean f(char[][] board,int i, int j, char[] str, int index)
    {
        if(str.length==index) // !! 这个判断一定要放在下面这个判断的前面,否则会报错,超出索引上界
        {
            return true;
        }
        if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=str[index])
        {
            return false;
        }
        
        board[i][j]='.';
        boolean b1 = f(board,i-1,j,str,index+1);
        boolean b2 = f(board,i,j-1,str, index+1);
        boolean b3 = f(board,i,j+1,str, index+1);
        boolean b4 = f(board,i+1,j,str, index+1);
        board[i][j] = str[index];
        return b1||b2||b3||b4;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值