用java代码 写广度优先搜索算法
时间: 2023-03-13 20:16:59 浏览: 61
答:public class BFS {
// function to print BFS traversal
public void BFS(int startVertex, int numOfVertices, int[][] adjacencyMatrix) {
// boolean array to store vertex visited or not
boolean[] visited = new boolean[numOfVertices]; // create a queue for Breadth First Traversal and enqueue starting vertex
Queue<Integer> queue = new LinkedList<>();
queue.add(startVertex);
visited[startVertex] = true; while (!queue.isEmpty()) {
// dequeue a vertex from queue and print it
startVertex = queue.poll();
System.out.print(startVertex + " "); // get all adjacent vertices of the dequeued vertex startVertex
// if an adjacent has not been visited, then mark it visited and enqueue it
for (int i = 0; i < numOfVertices; i++) {
if (adjacencyMatrix[startVertex][i] == 1 && !visited[i]) {
queue.add(i);
visited[i] = true;
}
}
}
}
}