leetcode79 (word search: DFS deep search)

Question: Given a two-dimensional grid and a word, find out whether the word exists in the grid.

Words must be in alphabetical order and formed by letters in adjacent cells, where "adjacent" cells are those that are adjacent horizontally or vertically. Letters in the same cell are not allowed to be reused.

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

Solution: Perform DFS deep search, traverse the two-dimensional array, and perform deep search and match with each element of the two-dimensional array as the starting point. If it can match successfully (can connect characters to get the same string as the word content), return true, if all Return false if the starting point cannot be matched successfully

class Solution {
    
    
     public boolean exist(char[][] board, String word) {
    
    
        for(int i=0;i< board.length;i++)
            for(int j=0;j<board[0].length;j++){
    
    
                if(DFS(board,i,j,word,new boolean[board.length][board[0].length],0))
                    return true;
            }
        return false;

    }
    /*
     * x、y用于记录当前board数组中被匹配的字符位置。   
     * checkPos用于记录word中被匹配的字符位置,若checkPos的值为word.length(),
     * 则说明匹配成功。
     * 二维数组searched用于记录元素的状态(是否被搜索)
     */
    private boolean DFS(char[][]board,int x,int y,String word,boolean[][]searched,int checkPos){
    
    
         if(checkPos==word.length())
            return true;
        else if(board[x][y]!=word.charAt(checkPos))
            return false;
       searched[x][y]=true;
        int[][]move={
    
    {
    
    0,1},{
    
    0,-1},{
    
    1,0},{
    
    -1,0}};
        boolean result=false;
        for(int[] temp:move){
    
    
            int X=x+temp[0];
            int Y=y+temp[1];
            if(X>=0&&X<board.length&&Y>=0&&Y<board.length) {
    
    
               if (!searched[X][Y]&&DFS(board, X, Y, word, searched, checkPos + 1)){
    
    
                        result = true;
                        break;
                }
            }
        }
        searched[x][y]=false;
        return result;
    }
}

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108569839