You are viewing a single comment's thread. Return to all comments →
Here is my solution using Adjacency Matrix
public static class Graph { int size; int[][] adjMatrix; public Graph(int size) { this.size = size; adjMatrix = new int[size][size]; } public void addEdge(int first, int second) { adjMatrix[first][second] = 1; adjMatrix[second][first] = 1; } public int[] shortestReach(int startId) { int[] distances = new int[size]; Arrays.fill(distances, -1); Queue<Integer> queue = new LinkedList<>(); queue.add(startId); distances[startId] = 0; while(!queue.isEmpty()){ int v = queue.remove(); for(int i =0;i<size;i++){ if(adjMatrix[v][i] == 1 && distances[i] == -1 ) { queue.add(i); distances[i] = distances[v]+6; } } } return distances; } }
Seems like cookies are disabled on this browser, please enable them to open this website
BFS: Shortest Reach in a Graph
You are viewing a single comment's thread. Return to all comments →
Here is my solution using Adjacency Matrix