高级农民
- 积分
- 2456
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-6-16
- 最后登录
- 1970-1-1
|
第五题,做起来发现倒也不难,刚看到完全懵懂
import java.util.*;
public class ManJump {
//第五题:是男人就跳问题
//给一个二维坐标平面和一个起始点,从这点开始垂直下跳,下面有若干水平挡板,位置长度会在input里给,板的形式是(x, y, distance),当跳到挡板上时,可以选择走到挡板的左端或者右端,然后继续垂直下跳,直到落地位置,求从开始到落地需要走过的路程最短是多少。
static int getShortestPath(int x, int y, List<Wood> list) {
list.sort((o1, o2) -> (o1.y - o2.y));
List<Point> workingList = new ArrayList<>();
Map<String, Integer> arriveNode = new HashMap<>();
Map<String, Integer> lastArriveNode = new HashMap<>();
int minPath = Integer.MAX_VALUE;
Point startPoint = new Point(x, y);
arriveNode.put(getPoint(startPoint), 0);
workingList.add(startPoint);
while (!workingList.isEmpty()) {
List<Point> tempList = new ArrayList<>();
for (Point point : workingList) {
int path = arriveNode.get(getPoint(point));
Wood nextWood = getNextWood(list, point.x, point.y);
if (nextWood == null) {
lastArriveNode.put(getPoint(point), arriveNode.get(getPoint(point)));
minPath = Math.min(minPath,arriveNode.get(getPoint(point)));
} else {
Point point1 = new Point(nextWood.x, nextWood.y);
Point point2 = new Point(nextWood.x + nextWood.distance, nextWood.y);
tempList.add(point1);
tempList.add(point2);
arriveNode.put(getPoint(point1), path + (point.x - nextWood.x));
arriveNode.put(getPoint(point2), path + (nextWood.x + nextWood.distance - point.x));
}
}
workingList = tempList;
}
return minPath;
}
private static Wood getNextWood(List<Wood> woods, int x, int y) {
for (Wood wood : woods) {
if (y > wood.y && x >= wood.x && x <= wood.x + wood.distance) {
//this is wood
return wood;
}
}
return null;
}
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
private static String getPoint(Point pt) {
return pt.x + ":" + pt.y;
}
public static void main(String[] args) {
List<Wood> woods = new ArrayList<>();
woods.add(new Wood(1,3,3));
woods.add(new Wood(3,4,5));
System.out.println(getShortestPath(3,4,woods));
}
static class Wood {
int x, y, distance;
public Wood(int x, int y, int distance) {
this.x = x;
this.y = y;
this.distance = distance;
}
}
}
|
|