Friday 19 April 2024

Shortest path in undirected graph with unit weight starting from start node via bfs

import java.util.*;
class Pair<Key, Value>{
    public Key first;
    public Value second;
    public Pair(Key first, Value second)
    {
        this.first=first;
        this.second=second;
    }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        ArrayList<Integer> arr = new ArrayList<>();
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(8,arr);
        addEdge(0,1,adj);
        addEdge(0,3,adj);
        addEdge(1,3,adj);
        addEdge(1,2,adj);
        addEdge(3,4,adj);
        addEdge(4,5,adj);
        addEdge(5,6,adj);
        addEdge(2,6,adj);
        addEdge(6,7,adj);
        addEdge(6,8,adj);
        addEdge(7,8,adj);
       
        System.out.println(adj);
        bfs(0,adj);
    }
   
    // Make adjList
    public static HashMap<Integer, ArrayList<Integer>> makeAdjList(int V, ArrayList<Integer> arr) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for(int i=0;i<V+1;i++)
        {
            adj.put(i,new ArrayList<Integer>()) ;
        }
        return adj;
    }
   
    // Add Edge
    public static void addEdge(int src, int dest, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
   
    // BFS traversal
    public static void bfs(int start, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        int V = adjList.size();
        int dist[] = new int[V];
        Arrays.fill(dist,Integer.MAX_VALUE);
        dist[0]=0;
        Queue<Pair<Integer,Integer>> q = new LinkedList<>();
        q.add(new Pair(0,0));
        while(!q.isEmpty())
        {
            int node=q.peek().first;
            int distance_node = q.peek().second;
            q.poll();
            for(int it: adjList.get(node))
            {
                if(distance_node + 1 < dist[it])
                {
                    dist[it]=distance_node + 1;
                    q.add(new Pair(it,distance_node + 1));
                }
            }
        }
        for(int it: dist)
        {
            System.out.print(it +" ");
        }
    }
}

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...