溫馨提示×

java尋路算法怎么實(shí)現(xiàn)

小億
100
2023-09-21 23:23:08
欄目: 編程語言

Java中的尋路算法可以使用圖的搜索算法來實(shí)現(xiàn)。以下是一個(gè)簡單的示例,使用BFS(廣度優(yōu)先搜索)算法來尋找路徑。

import java.util.*;
public class PathFinding {
// 定義圖的大小
private static final int ROW = 5;
private static final int COL = 5;
// 定義圖的節(jié)點(diǎn)
private static class Node {
int x;
int y;
Node parent;
public Node(int x, int y, Node parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
}
// 定義可移動(dòng)的方向
private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// 判斷點(diǎn)是否在圖內(nèi)
private static boolean isValid(int x, int y) {
return x >= 0 && x < ROW && y >= 0 && y < COL;
}
// 判斷點(diǎn)是否為障礙物(1表示障礙物)
private static boolean isObstacle(int[][] grid, int x, int y) {
return grid[x][y] == 1;
}
// 尋找路徑
public static List<Node> findPath(int[][] grid, Node start, Node end) {
List<Node> path = new ArrayList<>();
// 使用BFS算法
Queue<Node> queue = new LinkedList<>();
queue.offer(start);
boolean[][] visited = new boolean[ROW][COL];
visited[start.x][start.y] = true;
while (!queue.isEmpty()) {
Node curr = queue.poll();
if (curr.x == end.x && curr.y == end.y) {
// 找到目標(biāo)節(jié)點(diǎn),構(gòu)建路徑
while (curr != null) {
path.add(0, curr);
curr = curr.parent;
}
break;
}
// 遍歷可移動(dòng)的方向
for (int[] direction : DIRECTIONS) {
int newX = curr.x + direction[0];
int newY = curr.y + direction[1];
if (isValid(newX, newY) && !isObstacle(grid, newX, newY) && !visited[newX][newY]) {
Node next = new Node(newX, newY, curr);
queue.offer(next);
visited[newX][newY] = true;
}
}
}
return path;
}
public static void main(String[] args) {
// 定義一個(gè)示例地圖
int[][] grid = {
{0, 0, 0, 0, 0},
{1, 1, 1, 1, 0},
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 1},
{0, 0, 0, 0, 0}
};
Node start = new Node(0, 0, null);
Node end = new Node(4, 4, null);
List<Node> path = findPath(grid, start, end);
if (path.isEmpty()) {
System.out.println("No path found.");
} else {
System.out.println("Path found:");
for (Node node : path) {
System.out.println("(" + node.x + ", " + node.y + ")");
}
}
}
}

這個(gè)示例中,使用一個(gè)二維數(shù)組來表示地圖,0表示可通行的區(qū)域,1表示障礙物。findPath方法使用BFS算法來尋找路徑,返回一個(gè)包含節(jié)點(diǎn)的列表。最后在main方法中進(jìn)行測試,輸出找到的路徑。

0