剑指 Offer 13. 机器人的运动范围 + 深搜 + 递归
剑指 Offer 13. 机器人的运动范围
题目链接
package com.walegarrett.offer;
/**
* @Author WaleGarrett
* @Date 2020/12/9 9:49
*/
public class Offer_13 {
int m, n;
boolean[][] isTraveled;
int cnt;
int k;
int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public void dfs(int x, int y){
if(x < 0 ||x >=m || y<0 ||y>=n || isTraveled[x][y])
return;
else cnt++;
isTraveled[x][y] = true;
for(int i=0; i< 4; i++){
int dx = x+ direction[i][0];
int dy = y+ direction[i][1];
if(dx%10 + dx/10 + dy%10 + dy/10 <= k){
dfs(dx, dy);
}
}
}
public int movingCount(int m, int n, int k) {
this.m = m;
this.n = n;
cnt = 0;
isTraveled = new boolean[m][n];
this.k = k;
dfs(0, 0);
return cnt;
}
}
Either Excellent or Rusty