leetcode-机器人的运动范围

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 + "]";
		}
	}
}

复习了一下深度优先搜索

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值