0% found this document useful (0 votes)
14 views33 pages

DSA FirstPagejash

This lab report details the implementation of various data structures and algorithms as part of a Data Structures & Algorithms course. It includes experiments on stack and queue implementations, binary tree construction, and graph algorithms, along with source code and results for each implementation. The student, P. Jasmitha, completed these experiments under the guidance of Prof. Sri Geetha M.

Uploaded by

jasmithapilla79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views33 pages

DSA FirstPagejash

This lab report details the implementation of various data structures and algorithms as part of a Data Structures & Algorithms course. It includes experiments on stack and queue implementations, binary tree construction, and graph algorithms, along with source code and results for each implementation. The student, P. Jasmitha, completed these experiments under the guidance of Prof. Sri Geetha M.

Uploaded by

jasmithapilla79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

SCHOOL OF ARTIFICIAL INTELLIGENCE, DELHI NCR

Lab Report

Course Code & Title

23AID112 & Data Structures & Algorithms

Semester: II

Academic Year: 2024 – 2025 [Even]

STUDENT ROLL NO : DL.AI.U4AID24035


STUDENT NAME : P.JASMITHA

Faculty Coordinator: Prof. Sri Geetha M


TABLE OF CONTENTS

S.NO EXP.NO EXPERIMENT NAME MARKS SIGN

4 4 Stack Implementation & Application

a) Stack Implementation (Push/Pop etc.)

b) Stack Application (Infix to Postfix)

5 5 Queue Implementation

a) Normal Queue

b) Doubly Ended Queue

6 6 Binary Tree Implementation

a) Binary Tree (Arrays)

b) Binary Tree (Linked List)

7 7 Graph Algorithms

a) Graph Traversal using BFS, DFS

b) Dijkstra's Algorithm

TOTAL MARKS

AVERAGE
Exp. no: 4 Stack Implementation & Application

a) Stack Implementation (Push/Pop etc.)

AIM:
To implement a stack using an array in Java and perform basic operations: push, pop, peek, and isEmpty.

ALGORITHM:
Step 1: Start the Program.r
Step 2: Get the stack size (capacity) from the user.
Step 3: Create a stack array of the given size and initialize top = -1.
Step 4: Get elements from the user and push them onto the stack using a for loop.
Step 5: Pop the top element from the stack and display it.
Step 6: Display the current top element using peek().
Step 7: While the stack is not empty:
- Print the top element using peek()
- Remove it using pop()
Step 8: Display a message if the stack becomes empty.
Step 9: End the Program.

SOURCE CODE:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.IOException;

class stack1 {

int top, capacity;

int[] a;
public stack1(int capacity) {

this.capacity = capacity;

top = -1;

a = new int[capacity];

public boolean push(int x) {

if (top >= capacity - 1) {

System.out.println("Stack Overflow");

return false;

a[++top] = x;

return true;

public int pop() {

if (top < 0) {

System.out.println("Stack Underflow");

return 0;

return a[top--];

public int peek() {

if (top < 0) {

System.out.println("Stack is empty");

return 0;
}

return a[top];

public boolean isEmpty() {

return top < 0;

public class Stack_Implementation {

public static void main(String args[]) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

int n = Integer.parseInt(br.readLine());

stack1 s = new stack1(n);

System.out.println("Enter the elements: ");

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

int x = Integer.parseInt(br.readLine());

s.push(x);

System.out.println(s.pop() + " popped from stack");

System.out.println("Top element is: " + s.peek());

System.out.print("Remaining stack elements: ");

while (!s.isEmpty()) {

System.out.print(s.peek() + " ");

s.pop();
}

System.out.println();

OUTPUT:
RESULT:
Stack implemented successfully using array with basic operations.

b) Stack Application (Infix to Postfix)

AIM:
To convert a given infix expression into a postfix expression using a stack in Java.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the infix expression from the user.
Step 3: Create an empty stack for operators and a result string.
Step 4: For each character in the expression:

 If it's an operand, add it to the result.

 If it's '(', push to stack.


 If it's ')', pop from stack to result until '(' is found.
 If it's an operator:

 Pop operators from the stack with higher or equal precedence, and append to result.
 Then push the current operator.

Step 5: After the loop, pop all remaining operators from the stack and append to result.
Step 6: Print the postfix expression.
Step 7: End the program.

SOURCE CODE:
import java.util.*;
public class INFIX_TO_POSTFIX {
static boolean isop(char c) {
return Character.isLetterOrDigit(c);
}
static int precedence(char op) {
switch (op) {
case '^': return 3;
case '*': case '/': return 2;
case '+': case '-': return 1;
default: return -1;
}
}
static boolean isrightassoc(char op) {
return op == '^';
}
static String infixtopostfix(String expr) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : expr.toCharArray()) {
if (isop(c)) {
result.append(c).append(' ');
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop()).append(' ');
}
if (!stack.isEmpty() && stack.peek() == '(')
stack.pop();
} else { // operator
while (!stack.isEmpty() && stack.peek() != '(' &&
(precedence(stack.peek()) > precedence(c) ||
(precedence(stack.peek()) == precedence(c) && !isrightassoc(c)))) {
result.append(stack.pop()).append(' ');
}
stack.push(c);
}
}

while (!stack.isEmpty()) {
result.append(stack.pop()).append(' ');
}
return result.toString().trim();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter infix expression: ");
String infix = scanner.nextLine().replaceAll("\\s+", "");

String postfix = infixtopostfix(infix);


System.out.println("Postfix expression: " + postfix);
scanner.close();
}
}

OUTPUT:

RESULT:
Infix expression converted to postfix successfully.
Exp. no: 5 Queue Implementation

a) Normal Queue
AIM:

To implement a Normal Queue using an array in Java, supporting the operations:


Enqueue, Dequeue, Peek, and Display.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the size of the queue from the user.
Step 3: Initialize front = -1, rear = -1, and create a queue array of the given size.
Step 4: Display a menu with options:
 Enqueue:
- Check if rear == capacity - 1, then print "Queue Overflow".
- Else, insert the element at ++rear and set front = 0 if it's the first element.

 Dequeue:
- Check if the queue is empty (front == -1 || front > rear), then print "Queue Underflow".
- Else, print and remove the front element by incrementing front.

 Peek:
- If queue is empty, print "Queue is empty".
- Else, print the front element.

 Display:
- If queue is empty, print "Queue is empty".
- Else, print elements from front to rear.

Step 5: Repeat until the user chooses Exit.


Step 6: End the program.

SOURCE CODE:
import java.util.Scanner;
class Queue {
int front, rear, capacity;
int[] queue;

public Queue(int size) {


front = rear = -1;
capacity = size;
queue = new int[capacity];
}
public void enqueue(int data) {
if (rear == capacity - 1) {
System.out.println("Queue Overflow");
return;
}
if (front == -1) front = 0;
queue[++rear] = data;
System.out.println(data + " enqueued to queue.");
}
public void dequeue() {
if (front == -1 || front > rear) {
System.out.println("Queue Underflow");
return;
}
System.out.println(queue[front] + " dequeued from queue.");
front++;
}

public void peek() {


if (front == -1 || front > rear) {
System.out.println("Queue is empty");
} else {
System.out.println("Front element: " + queue[front]);
}
}

public void display() {


if (front == -1 || front > rear) {
System.out.println("Queue is empty");
} else {
System.out.print("Queue elements: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}
}
}
public class NQ {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of queue: ");
int size = sc.nextInt();
Queue q = new Queue(size);
while (true) {
System.out.println("\n1.Enqueue\n2.Dequeue\n3.Peek\n4.Display\n5.Exit");
System.out.print("Choose an option: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value to enqueue: ");
int val = sc.nextInt();
q.enqueue(val);
break;
case 2:
q.dequeue();
break;
case 3:
q.peek();
break;
case 4:
q.display();
break;
case 5:
System.out.println("Exiting...");
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}

OUTPUT:
RESULT:
Queue implemented successfully with basic operations.

b) Doubly Ended Queue

AIM:
To implement a double-ended queue (deque) using an array in Java, supporting insertion and deletion of
elements from both front and rear ends, along with displaying the deque contents interactively.

ALGORITHM:
Step 1: Start the program.
Step 2: Get the capacity of the deque from the user.
Step 3: Initialize the deque with front = -1, rear = -1, size = 0.
Step 4: Display menu options for Insert Front, Insert Rear, Delete Front, Delete Rear, Display, and Exit.
Step 5: Take user input for choice.
Step 6:

If choice is Insert Front, get value and insert at front.

If choice is Insert Rear, get value and insert at rear.

If choice is Delete Front, delete element from front.

If choice is Delete Rear, delete element from rear.

If choice is Display, show all deque elements.

If choice is Exit, terminate the program.


Step 7: Repeat Step 4 until user chooses Exit.
Step 8: End the program.

SOURCE CODE:
import java.util.Scanner;
public class doubledeque {
int[] arr;
int front, rear, size, capacity;
public doubledeque(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
front = -1;
rear = -1;
size = 0;
}
boolean isFull() {
return size == capacity;
}
boolean isEmpty() {
return size == 0;
}
void insertFront(int val) {
if (isFull()) {
System.out.println("Deque is full");
return;
}
if (isEmpty()) {
front = rear = 0;
} else {
front = (front - 1 + capacity) % capacity;
}
arr[front] = val;
size++;
System.out.println(val + " inserted at front.");
}

void insertRear(int val) {


if (isFull()) {
System.out.println("Deque is full");
return;
}
if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % capacity;
}
arr[rear] = val;
size++;
System.out.println(val + " inserted at rear.");
}
void deleteFront() {
if (isEmpty()) {
System.out.println("Deque is empty");
return;
}
int removed = arr[front];
arr[front] = 0; // optional clear
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % capacity;
}
size--;
System.out.println(removed + " deleted from front.");
}

void deleteRear() {
if (isEmpty()) {
System.out.println("Deque is empty");
return;
}
int removed = arr[rear];
arr[rear] = 0; // optional clear
if (front == rear) {
front = rear = -1;
} else {
rear = (rear - 1 + capacity) % capacity;
}
size--;
System.out.println(removed + " deleted from rear.");
}

void display() {
if (isEmpty()) {
System.out.println("Deque is empty");
return;
}
System.out.print("Deque elements: ");
for (int i = 0; i < size; i++) {
System.out.print(arr[(front + i) % capacity] + " ");
}
System.out.println();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter capacity of the deque: ");
int cap = sc.nextInt();

doubledeque deque = new doubledeque(cap);

while (true) {
System.out.println("\nChoose operation:");
System.out.println("1. Insert Front");
System.out.println("2. Insert Rear");
System.out.println("3. Delete Front");
System.out.println("4. Delete Rear");
System.out.println("5. Display Deque");
System.out.println("6. Exit");

System.out.print("Enter choice: ");


int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter value to insert at front: ");
int valFront = sc.nextInt();
deque.insertFront(valFront);
break;
case 2:
System.out.print("Enter value to insert at rear: ");
int valRear = sc.nextInt();
deque.insertRear(valRear);
break;
case 3:
deque.deleteFront();
break;
case 4:
deque.deleteRear();
break;
case 5:
deque.display();
break;
case 6:
System.out.println("Exiting...");
sc.close();
System.exit(0);
default:
System.out.println("Invalid choice! Try again.");
}
}
}
}

OUTPUT:

RESULT:
Deque operations performed successfully.
Exp. no: 6 Binary Tree Implementation

a) Binary Tree (Arrays)

AIM:
To construct a binary tree from a given array of integers in level-order, and perform in-order, pre-order, and
post-order traversals, along with a visual representation of the tree.

ALGORITHM:
Step 1: Start the Program.
Step 2: Create a Scanner object to read input from the user.
Step 3: Prompt the user to enter the size of the array.
Step 4: Read the array size and declare an array of that size.
Step 5: Prompt the user to enter the array elements.
Step 6: Use a for loop to read elements into the array.
Step 7: Declare a variable sum and initialize it to 0.
Step 8: Use a for loop to iterate through the array and add each element to sum.
Step 9: Display the final value of sum.
Step 10: End the Program.

SOURCE CODE:
import java.util.Scanner;
class TreeNode {
int data;
TreeNode l, r;
TreeNode(int value) {
data = value;
l = r = null;
}
}
public class binary_trees {
public static TreeNode buildtree(int[] arr, int i) {
if (i >= arr.length) return null;
TreeNode node = new TreeNode(arr[i]);
node.l = buildtree(arr, 2 * i + 1);
node.r = buildtree(arr, 2 * i + 2);
return node;
}

public static void printthetree(TreeNode root, int level) {


if (root == null) return;
printthetree(root.r, level + 1);
for (int i = 0; i < level; i++) System.out.print(" ");
System.out.println(root.data);
printthetree(root.l, level + 1);
}
public static void Inorder(TreeNode node) {
if (node == null) return;
Inorder(node.l);
System.out.print(node.data + " ");
Inorder(node.r);
}
public static void preorder(TreeNode node) {
if (node == null) return;
System.out.print(node.data + " ");
preorder(node.l);
preorder(node.r);
}
public static void postorder(TreeNode node) {
if (node == null) return;
postorder(node.l);
postorder(node.r);
System.out.print(node.data + " ");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of nodes: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " node values (level order):");
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
TreeNode root = buildtree(arr, 0);
System.out.println("\nVisualized Binary Tree:");
printthetree(root, 0);
System.out.print("\nIn-order: ");
Inorder(root);
System.out.print("\nPre-order: ");
preorder(root);
System.out.print("\nPost-order: ");
postorder(root);
scanner.close();
}
}

OUTPUT:
RESULT:
Binary tree implemented using array representation.

b) Binary Tree (Linked List)

AIM:
To build a binary tree from user input values provided as a linked list representation (level order) and
visually display the binary tree structure in a graphical window.

ALGORITHM:
Step 1: Start the program.

Step 2: Ask the user to enter the number of nodes in the linked list.

Step 3: Accept the node values one by one from the user and store them in an array.

Step 4: Convert the array representing the linked list into a binary tree using level order insertion:

 Create the root node with the first element.


 Use a queue to keep track of nodes whose children are yet to be assigned.

 For each node dequeued, assign the next array element as the left child (if exists).
 Assign the next array element as the right child (if exists).
 Enqueue newly created child nodes for further assignment.
Step 5: Initialize a GUI window (JFrame) and add a custom panel (JPanel) that draws the binary tree.

Step 6: In the custom panel:

 Use recursive drawing to paint each node as a circle.

 Draw connecting lines between parent and children’s nodes.


 Arrange nodes visually with appropriate spacing to represent tree levels.

Step 7: Display the GUI window showing the binary tree structure.

Step 8: End the program.

SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class TreeNode1 {
int data;
TreeNode1 left, right;
TreeNode1(int val) {
data = val;
}
}
public class Binary_LL extends JPanel {
private final TreeNode1 root;
private final int NODE_SIZE = 30;
private final int LEVEL_GAP = 50;

public Binary_LL(TreeNode1 root) {


this.root = root;
setPreferredSize(new Dimension(800, 600));
}

private void drawTree(Graphics g, TreeNode1 node, int x, int y, int xOffset) {


if (node == null) return;

g.setColor(Color.BLACK);
g.fillOval(x - NODE_SIZE / 2, y - NODE_SIZE / 2, NODE_SIZE, NODE_SIZE);
g.setColor(Color.WHITE);
g.drawString(String.valueOf(node.data), x - 6, y + 5);

g.setColor(Color.BLACK);
if (node.left != null) {
g.drawLine(x, y, x - xOffset, y + LEVEL_GAP);
drawTree(g, node.left, x - xOffset, y + LEVEL_GAP, xOffset / 2);
}
if (node.right != null) {
g.drawLine(x, y, x + xOffset, y + LEVEL_GAP);
drawTree(g, node.right, x + xOffset, y + LEVEL_GAP, xOffset / 2);
}
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawTree(g, root, getWidth() / 2, 40, getWidth() / 4);
}

private static TreeNode1 convertListToBinaryTree(int[] arr) {


if (arr.length == 0) return null;

TreeNode1 root = new TreeNode1(arr[0]);


Queue<TreeNode1> queue = new LinkedList<>();
queue.offer(root);

int i = 1;
while (i < arr.length) {
TreeNode1 parent = queue.poll();

// Left child
TreeNode1 leftChild = new TreeNode1(arr[i++]);
parent.left = leftChild;
queue.offer(leftChild);

// Right child if available


if (i < arr.length) {
TreeNode1 rightChild = new TreeNode1(arr[i++]);
parent.right = rightChild;
queue.offer(rightChild);
}
}
return root;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


int n = scanner.nextInt();

int[] arr = new int[n];


System.out.println("Enter " + n + " node values (linked list order):");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();

TreeNode1 root = convertListToBinaryTree(arr);


JFrame frame = new JFrame("Binary Tree Visualizer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Binary_LL(root));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

OUTPUT:

RESULT:
Binary tree created using linked list and traversed successfully.
Exp. no: 7 Graph Algorithms

a) Graph Traversal using BFS, DFS

AIM:
To develop a Java GUI application that takes graph input from the user and visualizes Breadth-First Search
(BFS) and Depth-First Search (DFS) traversals from node 0.

ALGORITHM:
Step 1: Start the program.

Step 2: Take graph input as edges (e.g., 0-1,1-2,2-3) from the user.

Step 3: Parse the input and build the graph using an adjacency list.

Step 4: On clicking BFS:

 Initialize a queue and visited set.


 Add the start node (0) to both.
 While the queue is not empty:

o Remove a node, display it.


o Add all unvisited neighbors to the queue.

Step 5: On clicking DFS:

 Initialize visited set.


 Use recursion:
o Visit a node, mark and display it.

o Recursively visit all unvisited neighbors.


Step 6: Add a short delay to simulate animation.

Step 7: Display traversal output in the text area.

Step 8: End the program.


SOURCE CODE:
package GraphTraversal;
import javax.swing.*;
import java.awt.BorderLayout;
import java.util.Map;
import java.util.HashMap;
import java.util.Queue;
import java.util.LinkedList;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
public class bfsanddfs extends JFrame {
private JTextField inputField;
private JTextArea outputArea;
private JButton bfsButton, dfsButton;
Map<Integer, java.util.List<Integer>> graph = new HashMap<>();
private int nodes;
public bfsanddfs() {
setTitle("Graph traversal visualizer");
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
inputField = new JTextField();
outputArea = new JTextArea();
bfsButton = new JButton("BFS");
dfsButton = new JButton("DFS");
outputArea.setEditable(false);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("Enter edges (e.g., 0-1,1-2,2-3):"), BorderLayout.NORTH);
panel.add(inputField, BorderLayout.CENTER);
JPanel buttons = new JPanel();
buttons.add(bfsButton);
buttons.add(dfsButton);
add(panel, BorderLayout.NORTH);
add(new JScrollPane(outputArea), BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
bfsButton.addActionListener(e -> {
buildgraph();
new Thread(() -> bfs(0)).start(); // Start from node 0
});
dfsButton.addActionListener(e -> {
buildgraph();
new Thread(() -> dfs(0)).start();
});
}
private void buildgraph() {
graph.clear();
outputArea.setText("");
String input = inputField.getText();
String[] edges = input.split(",");
for (String edge : edges) {
String[] nodes = edge.trim().split("-");
if (nodes.length == 2) {
int u = Integer.parseInt(nodes[0]);
int v = Integer.parseInt(nodes[1]);
graph.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
graph.computeIfAbsent(v, k -> new ArrayList<>()).add(u); // Undirected
}
}
}
private void bfs(int start) {
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited.add(start);
outputArea.append("bfs traversal:\n");
while (!queue.isEmpty()) {
int node = queue.poll();
outputArea.append("visited: " + node + "\n");
s();
for (int neighbor : graph.getOrDefault(node, new ArrayList<>())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
}
private void dfs(int start) {
Set<Integer> visited = new HashSet<>();
outputArea.append("DFS Traversal:\n");
dfsutil(start, visited);
}
private void dfsutil(int node, Set<Integer> visited) {
visited.add(node);
outputArea.append("Visited: " + node + "\n");
s();
for (int neighbor : graph.getOrDefault(node, new ArrayList<>())) {
if (!visited.contains(neighbor)) {
dfsutil(neighbor, visited);
}
}
}
private void s() {
try {
Thread.sleep(500); // Animation delay
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GraphTraversal.bfsanddfs().setVisible(true));
}
}

OUTPUT:

RESULT:
Graph traversals BFS and DFS performed successfully.

b) Dijkstra's Algorithm
AIM:
To implement Dijkstra's algorithm for finding the shortest paths from a given source vertex to all other
vertices in a weighted, directed graph, using user input for the graph structure.

ALGORITHM:
Step 1: Input number of vertices and edges.

Step 2: Create an adjacency list for the graph.

Step 3: Input each edge as: source, destination, weight.

Step 4: Input the source vertex.

Step 5: Initialize dist[] with infinite, parent [] with -1, and a priority queue.

Step 6: Set dist[source] = 0 and add source to the queue.

Step 7: While the queue is not empty:

 Extract vertex with smallest distance.


 Update distances and parents for neighbors if shorter paths found, add neighbors to queue.
Step 8: Print shortest distances, parents, and paths from source to each vertex.

SOURCE CODE:
package GraphTraversal;
import java.util.*;
public class DIJUSERinput {
static class Edge {
int d, w;
Edge(int dest, int weight) {
this.d = dest;
this.w = weight;
}

}
static class Node implements Comparable<Node> {
int ver, d;
Node(int vertex, int distance) {
this.ver = vertex;
this.d = distance;
}
public int compareTo(Node other) {
return this.d - other.d;
}
}
static class Graph {
int V;
List<List<Edge>> adjestList;
Graph(int V) {
this.V = V;
adjestList = new ArrayList<>();
for (int i = 0; i < V; i++)
adjestList.add(new ArrayList<>());
}
void addedge(int src, int dest, int weight) {
adjestList.get(src).add(new Edge(dest, weight));
}
void dij(int start) {
int[] dist = new int[V];
int[] parent = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
Arrays.fill(parent, -1);
dist[start] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(start, 0));
while (!pq.isEmpty()) {
Node current = pq.poll();
int u = current.ver;
for (Edge edge : adjestList.get(u)) {
int v = edge.d;
int weight = edge.w;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
parent[v] = u;
pq.add(new Node(v, dist[v]));
}
}
}
System.out.println("Vertex\tDistance\tPrevious");
for (int i = 0; i < V; i++) {
System.out.printf("%d %d %s\n", i, dist[i], parent[i] == -1 ? "-" : parent[i]);
}
System.out.println("\nShortest Paths from source:");
for (int i = 0; i < V; i++) {
if (i != start) {
System.out.print("Path to " + i + ": ");
printPath(i, parent);
System.out.println();
}
}
}

void printPath(int v, int[] parent) {


if (v == -1) return;
printPath(parent[v], parent);
System.out.print(v + " ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int vertices = sc.nextInt();
Graph g = new Graph(vertices);
System.out.print("Enter number of edges: ");
int edges = sc.nextInt();
System.out.println("Enter edges (source destination weight):");
for (int i = 0; i < edges; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
g.addedge(u, v, w);
}
System.out.print("Enter source vertex: ");
int source = sc.nextInt();
g.dij(source);
sc.close();
}
}

OUTPUT:

RESULT:
Shortest paths computed successfully using Dijkstra’s algorithm.

You might also like