LeetCode- word-search

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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word ="ABCCED", -> returnstrue,
word ="SEE", -> returnstrue,
word ="ABCB", -> returnsfalse.

public class Solution {
   public boolean exist(char[][] board, String word) {
        if (board == null || board.length==0) {
            return false;
        }
 
        int wlen = board.length;
        int nlen = board[0].length;
        int[][] visited = new int[wlen][nlen];
        for (int i = 0;i<wlen;i++) {
            for (int j=0;j<nlen;j++) {
                if(word.charAt(0)==board[i][j]){
                    visited[i][j] =1 ;
                    if(findWordDepthFirst(board,word,i,j,1,visited)){
                        return true;
                    }
                    visited[i][j] =0;
                }
            }
        }
        return false;
 
    }
    public boolean findWordDepthFirst(char[][] board,String word,int i,int j,int index,int[][] visited){
        if (index>=word.length()) {
            return true;
        }
        if (i>= board.length-1 && j>board[0].length){
            return false;
        }
        boolean flag = false;
        if (j < board[0].length-1 && visited[i][j+1]==0 && board[i][j+1]==word.charAt(index)){
            visited[i][j+1]=1;
            flag = findWordDepthFirst(board,word,i,j+1,index+1,visited);
            visited[i][j+1]=0;
        }
        if (flag == true){
            return true;
        }
        if (j >0 && visited[i][j-1]==0 && board[i][j-1]==word.charAt(index)){
            visited[i][j-1]=1;
            flag = findWordDepthFirst(board,word,i,j-1,index+1, visited);
            visited[i][j-1]=0;
        }
        if (flag == true){
            return true;
        }
        if (i < board.length-1 && visited[i+1][j]==0 && board[i+1][j]==word.charAt(index)){
            visited[i+1][j]=1;
            flag = findWordDepthFirst(board,word,i+1,j,index+1,visited);
            visited[i+1][j]=0;
        }
        if (flag == true){
            return true;
        }
        if (i > 0 && visited[i-1][j]==0 && board[i-1][j]==word.charAt(index)){
            visited[i-1][j]=1;
            flag =  findWordDepthFirst(board,word,i-1,j,index+1,visited);
            visited[i-1][j]=0;
        }
        return flag;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/89048157