시나리오는 플레이어가 소스 위치 A에서 B 위치로 이동해야하지만 최대량 만 이동할 수있는 턴 기반 상황입니다.가중치가없는 표에서 A에서 B 방향으로 최단 경로를 찾으려면 어떤 알고리즘을 사용해야합니까?
예를 들어, B는 A에서 24 단위 거리 (BFS를 사용하여 계산 됨)이며 12 점을 굴 렸습니다. B 방향으로 12 운동 단위 거리 밖에 떨어져 있지 않은 경로를 어떻게 찾을 수 있습니까?
참고 :
이- 가 이동할 수 없습니다 대각선
- 큰 장애물 이 있습니다
편집 :이 단서/클루 유사한 게임이지만, 텍스트 전용 그렇다 플레이어는 '앞으로'움직일 방향을 선택합니다. 여기
내가 뭘하려 :예 그리드 :
○○○○○○○○○○
○○○○○○○○◘◘
○○○◘◘◘○○◘◘
○○○◘◘◘○○B◘
○A○◘◘◘○○◘◘
알고리즘 (◘ 장애물이다, ○는 없습니다) :
if paces == 0, return
try moving col closer to dest.col:
if col == dest.col, move row closer to dest.row
else if adjacent is blocked, move row away from start
이를 제외하고, 종이에 괜찮 작동 내가 구석에 뛰어 들면 :
○A→◘◘○○◘◘◘
○○↓◘◘○○B◘◘
○○↓◘◘○○◘◘◘
○○↓◘◘○○↑◘◘
○○↓→→→→→◘◘
솔루션 :
public ArrayList<Location> shortestPath(final Location start, final Location dest) {
HashSet<Location> visits = new HashSet<>();
HashMap<Location, Location> links = new HashMap<>();
PriorityQueue<Location> queue = new PriorityQueue<>(Board.GRID_COLS * Board.GRID_ROWS,
new Comparator<Location>() {
@Override
public int compare(Location a, Location b) {
return Integer.compare(getHeuristic(a, dest), getHeuristic(b, dest));
}
});
queue.add(start);
while (!queue.isEmpty()) {
Location current = queue.remove();
if (current.equals(dest)) {
ArrayList<Location> path = reconstruct(current, new LinkedList<Location>(), links);
path.add(dest);
return path;
}
visits.add(current);
for (Location neighbour : getNeighbours(current)) {
if (!visits.contains(neighbour)) {
queue.add(neighbour);
visits.add(neighbour);
links.put(neighbour, current);
}
}
}
return null; // failed
}
// Manhattan distance
private int getHeuristic(Location src, Location dest) {
return Math.abs(dest.row - src.row) + Math.abs(dest.col - src.col);
}
private ArrayList<Location> reconstruct(Location current, LinkedList<Location> list, HashMap<Location, Location> links) {
if (links.containsKey(current)) {
list.addFirst(links.get(current));
return reconstruct(links.get(current), list, links);
} else {
return new ArrayList<>(list);
}
}
private ArrayList<Location> getNeighbours(Location current) {
ArrayList<Location> neighbours = new ArrayList<>();
if (current.row < GRID_ROWS - 1) {
Location n = LOCATIONS[current.row + 1][current.col];
if (isAccessible(n, current)) neighbours.add(n);
}
if (current.row > 0) {
Location n = LOCATIONS[current.row - 1][current.col];
if (isAccessible(n, current)) neighbours.add(n);
}
if (current.col < GRID_COLS - 1) {
Location n = LOCATIONS[current.row][current.col + 1];
if (isAccessible(n, current)) neighbours.add(n);
}
if (current.col > 0) {
Location n = LOCATIONS[current.row][current.col - 1];
if (isAccessible(n, current)) neighbours.add(n);
}
return neighbours;
}
A와 B 사이의 최단 경로를 취하고 그 12 단위로 충분하지 않습니까? –
http://en.wikipedia.org/wiki/Dijkstra's_algorithm – mariusnn
(최대, 최소값이 아님) –