leetcode刷题_OJ 79

参考博客:https://blog.csdn.net/happyaaaaaaaaaaa/article/details/50834335

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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

题目的意思:一开始我以为只是单纯地在grid中找到能表示该单词的字母集合即可,这样主要遍历一下grid来统计一下各单词出现次数与word进行比较即可。后来才发现,是要求能找出一条路径包含word,有则true,无则false。

这样看着就像一道dfs了,为了简化过程我们可以使用一个数组来标记该位置是否已经被访问,并且适当地进行剪枝:数组越界、该点已被访问、当前字母不匹配。

class Solution {
    public boolean exist(char[][] board, String word) {
        boolean[][] isVisited=new boolean[board.length][board[0].length];//标志该位置是否已进行访问
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[i].length;j++){
                if(IsExist(board,word,i,j,isVisited,0)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean IsExist(char[][] board, String word,int row,int col,boolean[][] isVisited,int index){
        int[] trow={0,1,0,-1};//行,右下左上
        int[] tcol={1,0,-1,0};//列,右下左上
        //先针对数组越界、已经被访问、当前字符不匹配进行剪枝
        if(row<0 || row>=board.length || col <0 || col>=board[0].length || isVisited[row][col] == true || board[row][col] != word.charAt(index)){
            return false;
        }
        //遍历结束,index等于word的长度返回true
        if(++index == word.length()){//要是index++会溢出
            return true;
        }
        isVisited[row][col]=true;
        for(int i=0;i<4;i++){//以board[row][col]为起点,向它的四周进行匹配
            if(IsExist(board,word,row+trow[i],col+tcol[i],isVisited,index)){
                return true;
            }
        }
        isVisited[row][col]=false;//遍历过后,该点未找到匹配的路径,将该点还原为未访问过
        return false;
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值