import java.util.ArrayList;import java.util.LinkedList;import java.util.Scanner; public class Main { public static void main(String[] args) { new Main().solve(); } private void solve() { Scanner scanner = new Scanner(System.in); int n = 6; int adj[][] = new int[n][n]; for (int i = 0; i < n; i++) { String[] strings= scanner.nextLine().split(" "); for (int j = 0; j < n; j++) { adj[i][j] =Integer.valueOf(strings[j]); } } Graph graph = new Graph(adj); graph.bfs(0); } static class Graph { int[][] adj; int nVerts; boolean[] visited; private Graph(int[][] adj) { this.adj = adj; this.nVerts = adj.length; this.visited = new boolean[nVerts]; } private void bfs(int start) { int[] dis=new int[nVerts]; for (int i = 0; i < nVerts; i++) { dis[i]=Integer.MAX_VALUE; } visited[start] = true; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); dis[start]=0; while (!queue.isEmpty()) { int v = queue.remove(); ArrayList<Integer> vs; vs =getNextVertex(v); for (Integer v1:vs){ int distance=adj[v][v1]; if (distance+dis[v]<dis[v1]) dis[v1]=distance+dis[v]; if (!visited[v1]) { queue.add(v1); visited[v1] = true; } } } for (int i = 0; i <nVerts; i++) { if (i!=0){ System.out.println(dis[i]); } } } private ArrayList<Integer> getNextVertex(int v) { ArrayList<Integer> adjVs = new ArrayList<>(); for (int i = 0; i < adj.length; i++) { if (i!=v&&adj[v][i] != -1) adjVs.add(i); } return adjVs; } }}
点赞 1

相关推荐

赏个offer求你了:友塔HR还专门加我告诉我初筛不通过😂
点赞 评论 收藏
分享
10-07 23:57
已编辑
电子科技大学 Java
八街九陌:博士?客户端?开发?啊?
点赞 评论 收藏
分享
牛客网
牛客企业服务