Sword finger offer - the range of motion of a robot

Problem description There is a grid of m rows and n columns on the ground, and a robot moves from the grid of coordinates (0,0), It can move left, rig...

Problem description

There is a grid of m rows and n columns on the ground, and a robot moves from the grid of coordinates (0,0), It can move left, right, up and down one grid at a time, but it can't enter the number of rows and columns For example, when k is 18, the robot can enter the grid (35, 37), because 3 + 5 + 3 + 7 = 18; But it can't enter the grid (35, 38), because 3 + 5 + 3 + 8 = 19. How many grids can the robot reach at most?

Problem analysis:

Backtracking method, each time to judge whether the up, down, left and right four directions meet the conditions

python code

# coding=utf-8 class Solution(object): ''' //There is a grid of m rows and n columns on the ground, and a robot moves from the grid of coordinates (0,0). //It can move left, right, up and down one grid at a time, but it can't enter the number of rows and columns //For example, when k is 18, the robot can enter the grid (35, 37), because 3 + 5 + 3 + 7 = 18; //But it can't enter the grid (35, 38), because 3 + 5 + 3 + 8 = 19. How many grids can the robot reach at most? ''' def solve(self, m, n, k): is_visited_array = [[False] * n] * m count = self.solve_count(0,0,is_visited_array, m, n, k) return count def solve_count(self, row, col, is_visited_array, m, n, k): count = 0 # print row,col if row >= 0 and col >= 0 and row < m and col < n and not is_visited_array[row][col] and self.is_sum(row, col, k) : # A goose utters its cry wherever it flies is_visited_array[row][col] = True # Top, bottom, left and right statistics count = 1 + self.solve_count(row - 1, col, is_visited_array, m, n, k) + self.solve_count(row, col - 1, is_visited_array, m, n, k) + \ self.solve_count(row + 1, col, is_visited_array, m, n, k) + self.solve_count(row, col + 1, is_visited_array, m, n, k) return count def is_sum(self, row, col, k): # Judge whether the sum of addition is in line with the rules row_sum = 0 col_sum = 0 while row > 10: row_sum += row / 10 row /= 10 row_sum += row while col > 10: col_sum += col / 10 col /= 10 col_sum += col return False if row_sum + col_sum > k else True if __name__ == '__main__': print Solution().solve(35, 37,18)

10 November 2019, 11:38 | Views: 1961

Add new comment

For adding a comment, please log in
or create account

0 comments