Pocket Gems 面经题 - Monkey Grid Problem

There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself? There is no input for this program. 

Print out the how many points can the monkey access. (The number should be printed as an integer whole number eg. if the answer is 10 (its not !!), print out 10, not 10.0 or 10.00 etc)

static class Point {
	int x, y;
	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof Point)) return false;
		Point pair = (Point) o;
		return x == pair.x && y == pair.y;
	}
	@Override
	public int hashCode() {
		return 31 * x + y;
	}
}

public static int digitSum(int n) {
	if(n < 0) n = -n;
	int sum = 0;
	while(n != 0) {
		sum += n % 10;
		n /= 10;
	}
	return sum;
}

private static int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

public static int countPoints(int k) {
	Set<Point> set = new HashSet<>();
	Queue<Point> queue = new LinkedList<>();
	queue.offer(new Point(0, 0));
	while(!queue.isEmpty()) {
		Point p = queue.poll();
		if(set.contains(p) || (digitSum(p.x) + digitSum(p.y)) > k) continue;
		set.add(p);
		for(int i=0; i<4; i++) {
			Point np = new Point(p.x+dir[i][0], p.y+dir[i][1]);
			if(!set.contains(np)) {
				queue.offer(np);
			}
		}
	}
	return set.size();
}

Reference:

http://www.careercup.com/question?id=13000687

http://blog.jverkamp.com/2013/08/30/visualizing-the-monkey-grid/

http://stackoverflow.com/questions/18133918/improve-the-solution-to-monkey-grid-puzzle

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值