Monday, 11 March 2024

GRAPH REPRESENTATION VIA ADJACENCY LIST IN JAVA & ADD EDGES

Method 1: Add manually

import java.util.*;

public class Wind {
    public static void main(String[] args) {
        HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<>();

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

        // Adding edges to the graph
        addEdge(adjList, 0, 1);
        addEdge(adjList, 1, 3);
        addEdge(adjList, 1, 2);
        addEdge(adjList, 0, 2);

        // Print the adjacency list
        System.out.println("Adjacency List: " + adjList);
    }

    // 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
    }
}


Method 2: Add when edges pre-given in form of 2-d matrix

import java.util.*;
public class Wind {
    public static void main(String[] args) {
        HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<>();

        // Adding nodes to the graph
        for (int i = 0; i < 4; i++) {
            adjList.put(i, new ArrayList<>());
        }
       
        int prerequisite[][] = {{0,1},{1,3},{1,2},{0,2}};
        for (int[] row : prerequisite)
        {
            int v=row[1];
            int u=row[0];
            addEdge(adjList,u,v); // u --> v
        }
        /*for (int[] row : prerequisite) {
            for (int element : row) {
                // Access the current element
                System.out.print(element + " ");
            }
            System.out.println(); // Move to the next line after each row
        }*/

        // Print the adjacency list
        System.out.println("Adjacency List: " + adjList);
    }
    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...