久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

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

共計(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ì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-12-20發(fā)表,共計(jì)1631字。
轉(zhuǎn)載說(shuō)明:除特殊說(shuō)明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請(qǐng)注明出處。
評(píng)論(沒(méi)有評(píng)論)
主站蜘蛛池模板: 客服| 鹿邑县| 汉源县| 军事| 炉霍县| 马公市| 兴宁市| 新和县| 山丹县| 郁南县| 平南县| 保康县| 铁力市| 西昌市| 广饶县| 遵义市| 嘉鱼县| 雅安市| 库伦旗| 通许县| 邯郸县| 沭阳县| 雷山县| 延庆县| 潜江市| 高台县| 常德市| 安顺市| 岑溪市| 西林县| 偃师市| 平遥县| 剑川县| 哈密市| 太仆寺旗| 柳州市| 平谷区| 濮阳市| 青州市| 安庆市| 漳浦县|