[topcoder]AvoidRoads

二维动态规划。和某一道leetcode的题目差不多。就是多了blocks的数组或集合。

本次解题的心得有:1.根据题意使用集合表示阻碍;2.使用字符串的形式表示整数的pair,简洁明了;3.p1到p2的阻碍其实是双向的;4.可以不用首行首列的全0;5.mx[i][j]和mx[i-1][j]和mx[i-1][j]可以分别加的。

import java.util.*;

public class AvoidRoads
{
	public long numWays(int width, int height, String[] bad) {
		HashMap<String,HashSet<String>> blocks = new HashMap<String,HashSet<String>>();
		for (String badStr : bad) {
			String[] bl = badStr.split(" ");
			int x1 = Integer.parseInt(bl[0]);
			int y1 = Integer.parseInt(bl[1]);
			int x2 = Integer.parseInt(bl[2]);
			int y2 = Integer.parseInt(bl[3]);
			String p1 = "" + x1+ ":" + y1;
			String p2 = "" + x2 + ":" + y2;
			// p1 -> p2 && p2-> p1 are blocked
			if (!blocks.containsKey(p1)) {
				HashSet<String> set = new HashSet<String>();
				blocks.put(p1, set);
			}
			if (!blocks.containsKey(p2)) {
				HashSet<String> set = new HashSet<String>();
				blocks.put(p2, set);
			}
			blocks.get(p1).add(p2);
			blocks.get(p2).add(p1);
		}
		long mx[][] = new long[width+1][height+1];
		
		for (int i = 0; i < width+1; i++) {
			for (int j = 0; j < height+1; j++) {
				if (i == 0 && j == 0) {
					mx[i][j] = 1;
				}
				else {
					String s0 = ""+i+":"+j;
					String s1 = ""+(i-1)+":"+j;
					String s2 = ""+i+":"+(j-1);
					if (i > 0 && !(blocks.containsKey(s1) && blocks.get(s1).contains(s0))) {
						mx[i][j] += mx[i-1][j];
					}
					if (j > 0 && !(blocks.containsKey(s2) && blocks.get(s2).contains(s0))) {
						mx[i][j] += mx[i][j-1];
					}
				}
			}
		}
		return mx[width][height];
	}
}

  

转载于:https://www.cnblogs.com/lautsie/p/3258732.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值