Sword finger offer -- the moving range of robot

Keywords: calculator

Summary

Title Description
There is a grid of m rows and n columns on the ground. A robot starts to move from the grid of coordinates 0,0. Each time, it can only move one grid to the left, right, up and down directions, but it can't enter the grid where the sum of the row coordinates and the column coordinates is 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 grid (35,38) because 3 + 5 + 3 + 8 = 19. How many squares can the robot reach?

thinking

This is a typical dfs problem. First, the access array isvisited is all 0, and the calculator cnt is 0. Then, first, judge whether the point (row,col) is in the coordinate range and is not accessed. If so, add 1 to cnt, and then isvisited[row][col] = 1. Next, repeat the four points around in the order of left, right, up and down, and perform dfs; otherwise, return directly.

C++ AC code

#include <iostream>
#include <cstring> 
using namespace std;

class Solution {
    private:
        int** isvisited;
        int cnt;
        int Rows;
        int Cols;
        int Threshold;
    public:
        int movingCount(int threshold, int rows, int cols){
            this->cnt = 0;
            this->Rows = rows;
            this->Cols = cols; 
            this->Threshold = threshold;
            isvisited = new int*[rows+1];
            for(int i = 0 ; i < rows+1 ; i++){
                isvisited[i] = new int[cols+1];
                memset(isvisited[i],0,sizeof(isvisited[0][0])*(cols+1));
            }
            int move[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};
            this->dfs(0,0,move);
            return this->cnt;
        }

        bool check(int row,int col){
            if(row < 0 || row >= this->Rows || col < 0 || col >= this->Cols){
                return false;
            }else{
                int sum1 = this->Caculate(row);
                int sum2 = this->Caculate(col);
                if(sum1+sum2 <= this->Threshold){
                    return true;
                }else{
                    return false;
                }
            }
        }

        int Caculate(int num){
            int sum = 0;
            while(num != 0){
                sum += num % 10;
                num /= 10;
            }
            return sum;
        }

        void dfs(int row,int col,int move[4][2]){
            if(this->check(row,col) && !this->isvisited[row][col]){
                this->cnt++;
                this->isvisited[row][col] = 1;
                for(int i = 0 ; i < 4 ; i++){
                    int r = row+move[i][0];
                    int c = col+move[i][1];
                    this->dfs(r,c,move);
                }
            }else{
                return;
            }
        }
}; 

Posted by terfle on Fri, 03 Jan 2020 22:16:24 -0800