leetcode-机器人的运动范围
题目传送门:题目链接
题目大意就是有一张m*n的地区,机器人从(0,0)的位置出发,期间不能移动到横纵坐标位数相加等于k的位置,问,机器人总共能够移动到的位置的总数。
其实就是一个深度优先搜索,程序从起点一直搜索,剪掉不能到达的位置,输出可到达的点的个数即可,我用的是Map记录的位置是否走过,后来发现,这里使用二维数组更省空间一点
class Solution {
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
public int movingCount(int m, int n, int k) {
int result = 0;
LinkedList<Location> queue = new LinkedList<Location>();
HashMap<String, Integer> map = new HashMap<String, Integer>();
//queue.addLast(null);
//queue.removeFirst();
Location start = new Location(0, 0);
queue.addLast(start);
result = result + 1;
map.put(start.toString(), 1);
while(queue.size()>0) {
Location now = queue.removeFirst();
for(int i = 0; i < 4; i++) {
int xx = now.x + dx[i];
int yy = now.y + dy[i];
Location next = new Location(xx, yy);
if((xx>=0)&&(xx<m)&&(yy>=0)&&(yy<n)&&(!map.containsKey(next.toString()))&&(sum(xx)+sum(yy)<=k)) {
map.put(next.toString(), 1);
result = result + 1;
queue.add(next);
}
}
}
return result;
}
public int sum(int x) {
int result = 0;
while(x > 0) {
int r = x % 10;
x = x / 10;
result = result + r;
}
return result;
}
class Location {
int x;
int y;
public Location(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Location [x=" + x + ", y=" + y + "]";
}
}
}
复习了一下深度优先搜索