The robot's range of motion java version, the specific content is as follows
There is a square of m rows and n columns on the ground. A robot starts to move from a grid with coordinates 0 and 0, and can only move one grid to the left, right, upper and lower directions at a time, but cannot enter a grid with the sum of the digits of the row coordinates and column coordinates greater than k. For example, when k is 18, the robot can enter the grid (35,37), because 3+5+3+7 = 18. However, it cannot enter the square (35,38), because 3+5+3+8 = 19. How many grids can the robot reach?
Problem solution:
1. First, determine whether the current position meets the entry conditions. If the entry conditions are met, continue to judge the four positions around it up, down, left and right (except the boundary). If not satisfied, it means that the current position selection is incorrect.
2. In each attempt, declare an array of flags to record the locations that have been visited.
3. There are three conditions for trying to continue: the coordinates are legal in the matrix, the coordinates meet the entry conditions, and the coordinate positions have not been accessed.
public class Solution { public int movingCount(int threshold, int rows, int cols) { if(threshold<0 || rows<=0 || cols<=0){ return 0; } int count = 0; boolean[] flag = new boolean[rows*cols]; for(int i=0; i<rows*cols; i++){ flag[i] = true; } count = Moving(threshold, 0, 0, rows, cols, flag); return count; } public int Moving(int t, int row, int col, int rows, int cols, boolean[] flag){ int count = 0; if(isAllow(t, row, col, rows, cols, flag)){ flag[row*cols+col] = false; count = 1+Moving(t, row-1, col, rows, cols, flag)+Moving(t, row, col-1, rows, cols, flag)+Moving(t, row+1, col, rows, cols, flag)+Moving(t, row, col+1, rows, cols, flag); } return count; } //Calculate the sum of the digits of the coordinates and return the comparison result with threshold public boolean isAllow(int t, int row, int col, int rows, int cols, boolean[] flag){ if(row>rows ||row<0 || col>cols || col<0 || row*cols+col>rows*cols-1|| flag[row*cols+col]==false){ return false; } int sum = 0; char[] chs = (row+"").toCharArray(); char[] chs1= (col+"").toCharArray(); for(char ch: chs){ sum += Character.getNumericValue(ch); } for(char ch1: chs1){ sum += Character.getNumericValue(ch1); } return sum<=t; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.