[leetcode] word-search

[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 {
    int row,col;
    public boolean exist(char[][] board, String word) {
        row=board.length;
        col=board[0].length;
        boolean[][] flag=new boolean[row][col];
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                if(dfs(board,word,i,j,0,flag)){
                    return true;
                }
            }
        }
        return false;
    }
    public boolean dfs(char[][] board, String word,int i,int j,int index,boolean[][] flag){
        if(index==word.length()){
            return true;
        }
        if(i<0||j<0||i>=row||j>=col){
            return false;
        }
        if(flag[i][j]){
            return false;
        }
        if(board[i][j]!=word.charAt(index)){
            return false;
        }
        flag[i][j]=true;
        boolean res=dfs(board,word,i-1,j,index+1,flag)||dfs(board,word,i+1,j,index+1,flag)||
            dfs(board,word,i,j-1,index+1,flag)||dfs(board,word,i,j+1,index+1,flag);
        flag[i][j]=false;
        return res;
    }
}

注:
深度优先遍历需要考虑占用资源的释放!

猜你喜欢

转载自blog.csdn.net/qq_41618373/article/details/83029416