LeetCode——79. Word Search

来源:互联网 发布:linux if语句 编辑:程序博客网 时间:2024/05/17 02:20

问题描述:

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.

  这道题目我刚开始也看不太懂,不知道他是啥意思(原谅我英语不太好)。后来仔细分析了一下,就是在这个二维数组中能否找到一串连续的元素,这串元素按选取的顺序构成的一个字符串等于word。所谓的一串连续的元素就是可以往上下左右走,不能斜着走,也不能选前面已经选过的元素,并且要按顺序的。

  这道题比较简单,就是考察图的深度遍历而已,使用递归,先选取一个等于该字符串首字符的点,然后递归尝试它的上下左右的点,与该字符串的下一个点进行比较,如果不满足条件(条件是:该选取点没有超出边界,没有被访问过,且值与字符串当前选取的字符相同)返回false,如果满足就选取这个点,继续递归尝试它的上下左右的点,直到最后,一直匹配完该字符串的所有字符,说明满足题目条件,返回true就可以了。同时因为它在图中无记忆的尝试,有可能会碰到我们已经选中的点,因此需要创建一个对应的二维数组,用来保存点是否被访问过的状态。在选取一个点时,需要在二维数组对应的位置将值设为1,取消选取这个点时设置为0。

直接上代码吧:

public boolean exist(char[][] board, String word) {        if(word == null || word.equals("") || board.length == 0)            return false;        int[][] isUsed = new int[board.length][board[0].length];        //在二维数组中选取与字符串第一个字符相等的点        for(int i = 0; i < board.length; i++) {            for(int j = 0; j < board[0].length; j++) {                //递归进行尝试,如果递归满足条件,直接返回true                if(depthSearch(0, i, j, word, isUsed, board))                    return true;            }        }        return false;    }    public boolean depthSearch(int curIndex, int i, int j, String word, int[][] isUsed, char[][] board) {        if(curIndex == word.length())            return true;        //如果当前点已超出数组边界,或者被访问过,亦或者当前点的值与字符串当前的字符不相等,返回false        if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || isUsed[i][j] == 1 || word.charAt(curIndex) != board[i][j])            return false;        //将这个点设为已选择        isUsed[i][j] = 1;        //然后递归尝试它的四个方向的点,只要有一个点可以就返回true        boolean result = depthSearch(curIndex+1, i+1, j, word, isUsed, board) ||            depthSearch(curIndex+1, i-1, j, word, isUsed, board) ||            depthSearch(curIndex+1, i, j+1, word, isUsed, board) ||            depthSearch(curIndex+1, i, j-1, word, isUsed, board);        //取消已选择的状态        isUsed[i][j] = 0;        return result;    }

  谢谢大家观看我的博客。如果大家有不明白的地方,或者文中有出错的地方,欢迎大家指出,谢谢!
  

原创粉丝点击