Range of motion LeetCode 46. Robot

Title Description

A ground checkered m rows and n columns, the coordinates [0,0] to the coordinate [m-1, n-1]. A robot [0, 0] from the coordinates of the grid begins to move, it can each left, right, up and down movement of a grid (not moved to the side exceptionally), can not enter the row and column coordinates of the sum is greater than the number of bits lattice k. For example, when k is 18, the robot can enter the box [35, 37], since the 3 + 3 + 5 + 7 = 18. But it can not enter the box [35, 38], since the 3 + 3 + 5 + 8 = 19. Will the robot be able to reach the number of lattice?

 

Example 1:

Input: m = 2, n = 3 , k = 1
Output: 3
Example 1:

Input: m = 3, n = 1 , k = 0
Output: 1
Note:

1 <= n,m <= 100
0 <= k <= 20

Problem-solving ideas

I started to understand the topic is, directly through the array, to see whether the sum is greater than the coordinate k, so with the following code

 public int movingCount(int m, int n, int k) {
        int[][] grid=new int[m][n];
        int result=0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                String numString=i+""+j;
                char[] chars=numString.toCharArray();
                int sum=0;
                for (int l = 0; l < chars.length; l++) {
                    sum+=Integer.valueOf(chars[l]+"");
                }
                if (sum<=k) {
                    result++;
                }
            }
        }
         return result;

        }
    

 

You can not run too

So to react, coordinate and in some places even less than k, but also make life difficult for the robot can not be counted

So we used DFS algorithm

code show as below

class Solution {
   boolean[][] visited;
     public int movingCount(int m, int n, int k) {
         visited = new boolean[m][n]; 
         return dfs(0, 0, m, n, k);
        

            }
     private int dfs(int x,int y,int m,int n,int k) {
          if (x>=m||y>=n||visited[x][y]||(x%10+x/10+y%10+y/10)>k) {
            return 0;
        }
          visited[x][y]=true;
          return 1+dfs(x+1, y, m, n, k)+dfs(x, y+1, m, n, k);
    }
}

 

Guess you like

Origin www.cnblogs.com/Transkai/p/12662065.html