package Graph;
import java.util.LinkedList;
import java.util.Queue;
public class BFS {
/**
* 图构建:1.邻接矩阵;2.邻接表
* 本实验是借助:邻接矩阵
* 辅助数组:
* color数组;-1 未访问; 0 进队列; 1:已经访问
* dist数组:表示距离源点的距离
* pred数组:表示前驱节点
* 描述:从源点出发,一次访问相邻节点。如图水中涟漪。用到的数据结构是:队列。可以用来计算无权图的最小距离。
* 非严格广搜,没有处理非连通图的情况,可以通过遍历城市+判断color数组来解决。
*/
public static void main(String[] args){
///
int numCity = 4;
int[][] graph = new int[numCity][numCity];
// int numPath = 4;
int[][] path = new int[][]{{1,2},{2,3},{1,3},{0,1}};
constructGraph(graph,path);
for (int i =0;i<graph.length;i++){
for(int j=0;j<graph[i].length;j++){
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
int[] color = new int[numCity]; // -1:未访问,0:入队列,1:访问
int[] dist = new int[numCity]; // -1:无法到达
int[] pred = new int[numCity]; // 每个城市的前驱城市
init(color,dist,pred); // 初始化辅助矩阵
BFS(graph,color,dist,pred); // 广搜
for(int i=1;i<dist.length;i++){ // 输出距离源点的距离,即为 无权图 最小距离
System.out.println(dist[i]);
}
for (int i=1;i<pred.length;i++){ // 输出前驱
System.out.println("城市"+ i + "的前驱城市:城市" +pred[i]);
}
}
public static void constructGraph(int[][] graph, int[][] path){
for (int i=0;i<path.length;i++){
graph[path[i][0]][path[i][1]] = 1;
graph[path[i][1]][path[i][0]] = 1;
}
}
public static void init(int[] color,int[] dist,int[] pred){
for (int i=0;i<color.length;i++){
color[i] = -1;
dist[i] = -1;
pred[i] = -1;
}
}
public static void BFS(int[][] graph,int[] color,int[] dist,int[] pred){
/**
* 广搜:实现技术 队列
* 从源点出发,访问与之相邻,且未被访问的城市,入队列。
*/
Queue<Integer> queue = new LinkedList<Integer>();
color[0] = 0;
queue.offer(0);
dist[0] = 0; //修改状态:入队列
while(!queue.isEmpty()){
int city = queue.poll(); //当前城市
for (int i=0;i<graph[city].length;i++){
// 判断第i城市
// 与city相邻的城市:已经访问的和在队列的都不用考虑了!
if (graph[city][i] == 1 && color[i] == -1){
queue.offer(i);
color[i] = 0; // 修改状态:入队列
dist[i] = dist[city] + 1;
pred[i] = city;
}
}
color[city] = 1; // 修改状态:已被访问
}
}
}
JAVA 与 图的广搜
最新推荐文章于 2023-02-19 17:29:34 发布