使用以下算法在java中实现bfs

h7appiyu  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(329)

我是java新手。有谁能请“用下面的算法在java中实现bfs”吗?
algorithm.jpg
要实现的代码:

import java.util.Scanner;
public class BFS{
   public static void main(String [] args){
      Scanner sc = new Scanner(System.in);
      int[][] graph = takeInputGraph(sc);
      System.out.println("Give input of the source node");
      int s = sc.nextInt();
      bfs(graph,s);
   }

   public static int[][] takeInputGraph(Scanner sc){
      System.out.println("Input the number of nodes in the graph");
      int node = sc.nextInt();
      System.out.println("Input the number of edges in the graph");
      int edge = sc.nextInt();
      int[][] mat = new int[node][node];
      for(int c=0; c<edge; c++){
         System.out.println("Enter the first node of the "+(c+1)+"th edge");
         int node1 = sc.nextInt();
         System.out.println("Enter the second node of the "+(c+1)+"th edge");
         int node2 = sc.nextInt();
         mat[node1][node2] = 1;
         mat[node2][node1] = 1;
      }
      return mat;
   }

   public static void bfs(int[][] g, int s){

   }
}
wf82jlnq

wf82jlnq1#

public static void bfs(int[][] g, int s){
    int[] d = new int[g.length], // distances 
          p = new int[g.length]; // previous node
    Arrays.fill(d, Integer.MAX_VALUE); // set all distances to infinity
    Arrays.fill(p, -1);
    d[s] = 0; // distance to starting node is 0
    Queue<Integer> q = new LinkedList<>();
    q.add(s);
    while(!q.isEmpty()){
        int u = q.poll();
        for(int v = 0; v < g.length; v++){
            if(g[u][v] == 1 // edge exists
                && d[u] + 1 < d[v]){ // distance is less
                d[v] = d[u] + 1;
                p[v] = u;
                q.add(v);
            }
        }
    }
}

相关问题