Sword refers to the motion range of the offer robot, and sword refers to the offer Robot
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8? Rp = 4 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
There is a square of m rows and n columns on the ground. A robot starts to move from the grid at coordinates 0, 0. Each time, it can only move one cell to the left, right, top, and bottom directions, however, you cannot enter a grid where the sum of the numbers of the row and column coordinates is greater than k. For example, when k is 18, the robot can enter the square (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 this robot reach?
Ideas
Search for basic questions in depth, and recursively solve the questions from 0 in four directions.
class Solution{public:int movingCount(int threshold, int rows, int cols){bool *vis = new bool[rows*cols];memset(vis,false,rows*cols);int ans = movingCountCore(threshold,rows,cols,0,0,vis);delete []vis;return ans;}int movingCountCore(int threshold, int rows, int cols,int x,int y,bool *vis){int count = 0;if(x>=0 && x<rows && y>=0 && y<cols && getSum(x)+getSum(y)<=threshold && !vis[x*cols+y]){vis[x*cols+y] = true;count = 1+movingCountCore(threshold,rows,cols,x-1,y,vis) +movingCountCore(threshold,rows,cols,x+1,y,vis) +movingCountCore(threshold,rows,cols,x,y-1,vis) +movingCountCore(threshold,rows,cols,x,y+1,vis);}return count;}int getSum(int x){int sum = 0;while(x){sum+=x%10;x/=10;}return sum;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source