1 问题
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
提示:
1 <= n,m <= 100
0 <= k <= 20
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 方案
BFS就行了。
from collections import deque
class Solution:
def check(self,x,y,m,n):
if (x>=0 and x<m) and (y>=0 and y<n):
return True
return False
def get_sum(self,x):
res = 0
while x > 0:
res += x%10
x = x//10
return res
def movingCount(self, m: int, n: int, k: int) -> int:
# start
q = deque()
sx = 0
sy = 0
q.append((sx,sy,0))
visited = set([(sx,sy)])
res = 1
while (len(q)>0):
cnt = len(q)
for _ in range(cnt):
x,y,num = q.popleft()
directions = [(1,0),(0,1)]
for d in directions:
nx = x+d[0]
ny = y+d[1]
if self.check(nx,ny,m,n):
nnum = self.get_sum(nx) + self.get_sum(ny)
if (nx,ny) not in visited:
visited.add((nx,ny))
if nnum <= k:
q.append((nx,ny,nnum))
res += 1
return res
Java:
本来想用 hashset 去记录visited的点Node,但是,发现 contains 方法不work,有点迷惑。
import java.util.* ;
class Solution {
class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
public int get_sum(int x){
int res = 0;
while(x>0){
res += x%10;
x = (int) (x/10);
}
return res;
}
public boolean check(int x, int y, int k){
if(get_sum(x)+get_sum(y) <= k){
return true;
}
return false;
}
public int movingCount(int m, int n, int k) {
LinkedList<Node> queue = new LinkedList<Node>();
Node start = new Node(0,0);
queue.add(start);
int[] dx = new int[]{1,0};
int[] dy = new int[]{0,1};
boolean[][] visited = new boolean[m][n];
int res = 1;
while (!queue.isEmpty()){
for(int i=0;i<queue.size();i++){
Node q = queue.poll();
int x = q.x;
int y = q.y;
for(int j=0; j<dx.length; j++){
int nx = x+dx[j];
int ny = y+dy[j];
if(((nx>=0) & (nx<m)) & ((ny>=0) & (ny<n))){
if(!visited[nx][ny]){
visited[nx][ny] = true;
if(check(nx,ny,k)){
Node nq = new Node(nx,ny);
queue.add(nq);
res += 1;
}
}
}
}
}
}
return res;
}
}