JZ13 机器人的运动范围

题目描述:
在这里插入图片描述

思路:使用深度优先(dfs)搜索方法
从[0,0]开始,每次选择一个方向开始检查能否访问,如果能访问进入该节点,该节点作为子问题,继续按照这个思路访问,一条路走到黑,然后再回溯,回溯的过程中每个子问题再选择其他方向,正是深度优先搜索。

具体步骤:
step 1:检查若是threshold小于等于0,只能访问起点这个格子。
step 2:从起点开始深度优先搜索,每次访问一个格子的下标时,检查其有没有超过边界,是否被访问过了。同时用连除法分别计算每个下标的位数和,检查位数和是否大于threshold。
step 3:若是都符合访问条件,则进行访问,增加访问的格子数,同时数组中标记为访问过了。
step 4:然后遍历四个方向,依次进入四个分支继续访问。

这里要定义一个数组,表示每次遍历的四个方向,int[][] dir = { {-1,0},{1,0},{0,-1},{0,1}};
其中包含了四组坐标偏移量。每组偏移量表示在二维平面上朝四个不同方向移动时的行和列的变化量。具体来说,{ {-1, 0}}
表示向上移动一行,{ {1, 0}} 表示向下移动一行,{ {0, -1}} 表示向左移动一列,{ {0, 1}}
表示向右移动一列。这种表示方式常用于在二维网格或矩阵中进行相对位置的操作,比如搜索相邻元素或者进行遍历操作。

代码:

import java.util.*;
public class Solution {
    
    
    int[][] dir = {
    
    {
    
    -1,0},{
    
    1,0},{
    
    0,-1},{
    
    0,1}};//记录遍历的四个方向
    int res = 0;
    int cal(int n){
    
    
        int sum = 0;
        //连除法计算每一位数字
        while(n!=0){
    
    
            sum += (n%10);
            n /= 10;
        }
        return sum;
    }
    void dfs(int i,int j,int rows,int cols,int threshold,boolean[][] vis){
    
    
        if(i<0||i>=rows||j<0||j>=cols||vis[i][j]==true){
    
    
            return;
        }
        if(cal(i)+cal(j)>threshold){
    
    
            return;
        }
        res += 1;
        vis[i][j]=true;
        for(int k=0;k<4;k++){
    
    
            dfs(i+dir[k][0],j+dir[k][1],rows,cols,threshold,vis);
        }
    }
    public int movingCount(int threshold, int rows, int cols) {
    
    
        if(threshold<=0){
    
    
            return 1;
        }
        boolean[][] vis = new boolean[rows][cols];
        dfs(0,0,rows,cols,threshold,vis);
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45257495/article/details/132589087