BFS With Colors

import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static class Graph { List<Integer>[] graph; public Graph(int size) { graph = new List[size + 1]; } public void addEdge(int first, int second) { if (graph[first] == null){ graph[first] = new ArrayList<>(); } graph[first].add(second); if (graph[second] == null){ graph[second] = new ArrayList<>(); } graph[second].add(first); } public int[] shortestReach(int startId) { return hasPathBFS(startId); } // Helper recursive BFS method private int[] hasPathBFS(int source){ final int WHITE = 0; final int GRAY = 1; final int BLACK = 2; final int weight = 6; int[] colors = new int[graph.length]; int[] distance = new int[graph.length]; LinkedList<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < graph.length; i++) { colors[i] = 0; distance[i] = -1; } colors[source] = WHITE; distance[source] = 0; queue.add(source); while (!queue.isEmpty()) { int currentNode = queue.pop(); for (int neighbour : graph[currentNode]) { if (colors[neighbour] == WHITE) { colors[neighbour] = GRAY; distance[neighbour] = distance[currentNode] + weight; queue.add(neighbour); } } colors[currentNode] = BLACK; } return distance; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int queries = scanner.nextInt(); for (int t = 0; t < queries; t++) { // Create a graph of size n where each edge weight is 6: Graph graph = new Graph(scanner.nextInt()); int m = scanner.nextInt(); // read and set edges for (int i = 0; i < m; i++) { int u = scanner.nextInt(); int v = scanner.nextInt(); // add each edge to the graph graph.addEdge(u, v); } // Find shortest reach from node s int startId = scanner.nextInt(); int[] distances = graph.shortestReach(startId); for (int i = 1; i < distances.length; i++) { if (i != startId) { System.out.print(distances[i]); System.out.print(" "); } } System.out.println(); } scanner.close(); } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.