Thematic backtracking Leetcode of -79. Word Search (Word Search)

Thematic backtracking Leetcode of -79. Word Search (Word Search)


 

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

Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.

Example:

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

given word = "ABCCED", returns true. 
given word = "SEE", returns true. 
given word = "ABCB", returns false.



Analysis:
Given a map, find a path after a period (up, down, left, right) can form a given word.
A problem classic maps + back type of problem, the question needs a vis array to control whether the map has gone through,
to ensure that no turning back.
vis [x] [y] = 1 when the traveled before, do not go.
vis [x] [y] = 0 indicates not gone before, can go.


AC Code:
class Solution {
   boolean flag = false;
    int dirx[] = new int[]{1,-1,0,0};
    int diry[] = new int[]{0,0,1,-1};
    public boolean exist(char[][] board, String word) {
        if(board.length==0 || word.equals("")){
                return false;
        }
        char first = word.charAt(0);
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(board[i][j]==first){
                    int vis[][] = new int[board.length][board[0].length];
                    vis[i][j] = 1;
                    dfs(board,vis,i,j,word,1);
                    vis[i][j] = 0;
                }
            }
        }
        return flag;
    }
    
    public void dfs(char[][] board,int vis[][],int x,int y,String word,int now){
        if(now == word.length()){
            flag = true;
            return;
        }
        if(flag) return;
        
        int m = board.length;
        int n = board[0].length;
        
        for(int i=0;i<4;i++){
            int xx = x + dirx[i];
            int yy = y + diry[i];
            if(xx>=0 && xx<m && yy>=0 && yy<n && vis[xx][yy]==0 && board[xx][yy]==word.charAt(now)){
                vis[xx][yy] = 1;
                dfs(board,vis,xx,yy,word,now+1);
                vis[xx][yy] = 0;
            }
        }
        
        
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11330171.html