矩阵中的路径(dfs+剪枝、bfs)

在这里插入图片描述

class Solution {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board,char[] words,int i,int j,int k){
        if(i>=board.length || i<0 || j>=board[0].length || j<0 || board[i][j]!=words[k]){
            return false;
        }
        if(k == words.length-1){
            return true;
        }
        board[i][j] = '\0';
        boolean res = dfs(board,words,i+1,j,k+1) || dfs(board,words,i-1,j,k+1) || 
                    dfs(board,words,i,j+1,k+1) || dfs(board,words,i,j-1,k+1);
        board[i][j] = words[k];
        return res;
    }
}

在这里插入图片描述

dfs
class Solution {
    public int movingCount(int m, int n, int k) {
        boolean[][] num = new boolean[m][n];
        return dfs(num,m,n,k,0,0);
    }
    int dfs(boolean[][] num ,int m, int n, int k, int i, int j){
        if(i>=m || i<0 || j>=n || j<0 || num[i][j] || sum(i,j)>k){
            return 0;
        }
        num[i][j] = true;
        int res1 = dfs(num,m,n,k,i+1,j);
        int res2 = dfs(num,m,n,k,i-1,j);
        int res3 = dfs(num,m,n,k,i,j+1);
        int res4 = dfs(num,m,n,k,i,j-1);
        return 1+res1+res2+res3+res4;
    }

    int sum(int m,int n){
        int a1 = m/10;
        int a2 = m%10;
        int a3 = n/10;
        int a4 = n%10;
        return a1+a2+a3+a4;
    }
}
bfs
class Solution {
    public int movingCount(int m, int n, int k) {
        boolean[][] visited = new boolean[m][n];
        int res = 0;
        Queue<int[]> queue= new LinkedList<int[]>();
        queue.add(new int[] { 0, 0, 0, 0 });
        while(queue.size() > 0) {
            int[] x = queue.poll();
            int i = x[0], j = x[1], si = x[2], sj = x[3];
            if(i >= m || j >= n || k < si + sj || visited[i][j]) continue;
            visited[i][j] = true;
            res ++;
            queue.add(new int[] { i + 1, j, (i + 1) % 10 != 0 ? si + 1 : si - 8, sj });
            queue.add(new int[] { i, j + 1, si, (j + 1) % 10 != 0 ? sj + 1 : sj - 8 });
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值