广度优先搜索java
时间: 2023-11-12 08:59:55 浏览: 44
好的,关于广度优先搜索的Java实现,可以参考以下代码:
```java
import java.util.*;
public class BFS {
public static void main(String[] args) {
int[][] graph = {{0, 1, 1, 0, 0},
{1, 0, 0, 1, 1},
{1, 0, 0, 1, 0},
{0, 1, 1, 0, 1},
{0, 1, 0, 1, 0}};
bfs(graph, 0);
}
public static void bfs(int[][] graph, int start) {
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[graph.length];
queue.offer(start);
visited[start] = true;
while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
for (int i = 0; i < graph.length; i++) {
if (graph[node][i] == 1 && !visited[i]) {
queue.offer(i);
visited[i] = true;
}
}
}
}
}
```
这是一个简单的无权图的广度优先搜索实现,使用了队列来存储待访问的节点,使用了一个布尔数组来记录每个节点是否被访问过。