Friday 19 April 2024

BFS traversal of graph represented by adjacency list

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<>();

        // Adding nodes to the graph
        for (int i = 0; i <= 9; i++) {
            adjList.put(i, new ArrayList<>());
        }

        // Adding edges to the graph
        addEdge(adjList, 0, 1);
        addEdge(adjList, 1, 2);
        addEdge(adjList, 1, 6);
        addEdge(adjList, 2, 3);
        addEdge(adjList, 2, 4);
        addEdge(adjList, 6, 7);
        addEdge(adjList, 4, 5);
        addEdge(adjList, 6, 9);
        addEdge(adjList, 7, 8);

        // Print the adjacency list
        System.out.println("Adjacency List: " + adjList);
        System.out.println("The bfs traversal is:");
        ArrayList < Integer > ans = bfsOfGraph(9, adjList);
        int n = ans.size();
        for(int i = 0;i<n;i++) {
            System.out.print(ans.get(i)+" ");
        }
    }
    public static ArrayList<Integer> bfsOfGraph(int V, HashMap<Integer, ArrayList<Integer>> adjList) { // V is last number(max num) of graph
        ArrayList < Integer > bfs = new ArrayList < > ();
        boolean vis[] = new boolean[V+1];
        Queue < Integer > q = new LinkedList < > ();
        q.add(0);
        vis[0] = true;
        while (!q.isEmpty()) {
            int node = q.poll();
            bfs.add(node);
            for (int it: adjList.get(node)) {
                if (vis[it] == false) {
                    vis[it] = true;
                    q.add(it);
                }
            }
        }

        return bfs;
    }
   
   
    // Helper method to add an edge to the graph
    public static void addEdge(HashMap<Integer, ArrayList<Integer>> adjList, int source, int destination) {
        adjList.get(source).add(destination);
        adjList.get(destination).add(source); // If the graph is undirected
    }
}

No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...