leetcode 79. 单词搜索【DFS、回溯】

题目要求需要在网格中的相邻单元格内按顺序找到给定单词的字母。在单词中相邻的字母需要也需要在网格中相邻,因此可以采用DFS来对网格进行搜索。
使用一个辅助二维数组来记录网格中某个元素是否已经被访问,而且当搜索到某一地方发现不满足要求时,需要返回上一层搜索并取消该元素被访问的标记,即回溯。

class Solution {
    int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(dfs(board, visited, word, i, j, 0, m, n))return true;
            }
        }
        return false;
    }
    
    public boolean dfs(char[][] board, boolean[][] visited, String word, int i, int j, int index, int m, int n){
        if(index == word.length()-1){
            return word.charAt(index) == board[i][j];
        }
        
        if(board[i][j] == word.charAt(index)){
            visited[i][j] = true;
            for(int k=0; k<4; k++){
                int x = i+dir[k][0];
                int y = j+dir[k][1];
                if(inArea(x, y, m, n) && !visited[x][y]){
                    if(dfs(board, visited, word, x, y, index+1, m, n))return true;
                }
            }
            //回溯
            visited[i][j] = false;
        }
        return false;
    }
    
    public boolean inArea(int x, int y, int m, int n){
        return x>=0 && y>=0 && x < m && y< n;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值