題目描述
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
思路:將地圖全部置1,遍歷能夠到達的點,將遍歷的點置0並令計數+1.這個思路在找前後左右相連的點很有用,比如leetcode中的海島個數問題/最大海島問題都可以用這種方法來求解。
python
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.count = 0
def movingCount(self, threshold, rows, cols):
# write code here
arr = [[1 for i in range(cols)] for j in range(rows)]
self.findway(arr, 0, 0, threshold)
return self.count
def findway(self, arr, i, j, k):
if i < 0 or j < 0 or i >= len(arr) or j >= len(arr[0]):
return
tmpi = list(map(int, list(str(i))))
tmpj = list(map(int, list(str(j))))
if sum(tmpi) + sum(tmpj) > k or arr[i][j] != 1:
return
arr[i][j] = 0
self.count += 1
self.findway(arr, i + 1, j, k)
self.findway(arr, i, j + 1, k)
c++
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
bool *flag = new bool[rows * cols];
for(int i = 0; i < rows * cols; i++)
flag[i] = false;
int count = moving(threshold, rows, cols, 0, 0, flag);
return count;
}
int moving(int threshold, int rows, int cols, int i, int j, bool* flag)
{
int count = 0;
if(i >= 0 && i < rows && j >= 0 && j < cols && getsum(i) + getsum(j) <= threshold && flag[i * cols + j] == false)
{
flag[i * cols + j] = true;
count =1 + moving(threshold, rows, cols, i + 1, j, flag)
+ moving(threshold, rows, cols, i - 1, j, flag)
+ moving(threshold, rows, cols, i , j - 1, flag)
+ moving(threshold, rows, cols, i, j + 1, flag);
}
return count;
}
int getsum(int num)
{
int sum = 0;
while(num)
{
sum += num % 10;
num /= 10;
}
return sum;
}
};