《leetCode》:Word Search

来源:互联网 发布:mac os x 开机启动项 编辑:程序博客网 时间:2024/05/18 16:35

题目

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.

题目大意:在一个二维数组中,是否含有指定的字符串,指定的字符串由二维数组中相邻的字符构成,注:这里的相邻包括“上下左右相邻”。

思路

这个题是一个好题,自己想了半天没有想出来。下面的思路来自于leetCode这个题后面的讨论。

利用递归遍历搜索法,当在board[x][y]处遍历到word[start]字符后,然后在board位置(x,y)的上下左右检查是否出现了word[++start]这个字符,直到start>=word.length;就说明board二维数组中是存在这个字符串的。

实现代码如下:

public class Solution {    //函数的功能,检查从矩阵board的位置x,y处是否有满足从start下标开始的word    public boolean exist(char[][]board,int x,int y,String word,int start){        if(start>=word.length()) return true;//这种情况,说明找到了符合word的单词        if(x<0||x>=board.length||y<0||y>=board[0].length) return false;        if(board[x][y]==word.charAt(start++)){//先满足第start个字符,才开始检查start后面的字符,            char temp=board[x][y];            board[x][y]='#';//用一个特殊的字符来标记已经遍历过的位置            //检查范围为,(x,y)的上下左右            boolean res=exist(board,x-1,y,word,start)||exist(board,x+1,y,word,start)||exist(board,x,y-1,word,start)||exist(board,x,y+1,word,start);            board[x][y]=temp;            return res;        }        return false;    }    public boolean exist(char[][] board, String word) {        if(board==null||board.length<1){            return false;        }        int len=board.length;        for(int i=0;i<len;i++){            for(int j=0;j<board[0].length;j++){                if(exist(board,i,j,word,0)) return true;            }        }        return false;    }}
0 0