共計(jì) 1631 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。
Java 中的尋路算法可以使用圖的搜索算法來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例,使用 BFS(廣度優(yōu)先搜索)算法來(lái)尋找路徑。
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 = 0 && y < COL;}
// 判斷點(diǎn)是否為障礙物(1 表示障礙物)private static boolean isObstacle(int[][] grid, int x, int y) {return grid[x][y] == 1;
}
// 尋找路徑
public static List findPath(int[][] grid, Node start, Node end) {List path = new ArrayList();
// 使用 BFS 算法
Queue 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 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ù)組來(lái)表示地圖,0 表示可通行的區(qū)域,1 表示障礙物。findPath
方法使用 BFS 算法來(lái)尋找路徑,返回一個(gè)包含節(jié)點(diǎn)的列表。最后在 main
方法中進(jìn)行測(cè)試,輸出找到的路徑。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完