Sunday, 1 October 2023

Graph representation(Both directed and undirected) using adjacency list (code in JAVA)


import java.util.ArrayList;

import java.util.Scanner;


public class graph {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        // Input the number of nodes.

        System.out.print("Enter the number of nodes: ");

        int numNodes = scanner.nextInt();


        // Create an adjacency list.

        ArrayList<ArrayList<Integer>> adjList = new ArrayList<>(numNodes);


        for (int i = 0; i < numNodes + 1; i++) { // numNodes + 2 only if remove empty zero index 

            adjList.add(new ArrayList<>());

        }


        // Input the number of edges.

        System.out.print("Enter the number of edges: ");

        int numEdges = scanner.nextInt();


        // Input the edges (connections between nodes).

        System.out.println("Enter the edges (startNode endNode):");

        for (int i = 0; i < numEdges; i++) {

            int startNode = scanner.nextInt();

            int endNode = scanner.nextInt();


            // Add an edge from startNode to endNode (for directed graph).

            adjList.get(startNode).add(endNode);


            // For undirected graph, add the reverse edge as well.

            // adjList.get(endNode).add(startNode); // Uncomment this line for an undirected graph.

        }


        // Print the adjacency list.

        System.out.println("Adjacency List:");

        for (int i = 1; i < numNodes + 1; i++) {

            System.out.print(i + " -> ");

            for (int neighbor : adjList.get(i)) {

                System.out.print(neighbor + " ");

            }

            System.out.println();

        }


        scanner.close();

    }

}


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