All posts by Ankur

Implementation of Multi-Stage Graph in Java

In this post, we’ll explore how to implement a Multi-Stage Graph in Java — a specialized graph where each stage (or node) has connections to only certain other stages, and the goal is to find the optimal path and cost through the stages.

What is a Multi-Stage Graph?

A Multi-Stage Graph is a graph where the nodes are grouped into distinct stages, and each node can only connect to the next stage in the sequence. The algorithm finds the minimum cost and optimal path from the start node (source) to the end node (destination).

In this post, we’ll focus on two methods to compute the optimal path:

  1. Forward Method: Compute the cost and parent nodes starting from the destination.
  2. Backward Method: Compute the cost and parent nodes starting from the source.

How the Multi-Stage Graph Algorithm Works

  1. Graph Representation:
    The graph is represented using a 2D matrix where x[i][j] denotes the weight or cost of the edge from node i to node j. A value of 0 means there is no direct edge between the nodes.
  2. Cost Calculation:
    • In the Forward Method, we start from the destination node and move backward to compute the cost for each stage.
    • In the Backward Method, we start from the source node and compute the cost to each destination node.
  3. Optimal Path:
    The algorithm tracks the parent node for each stage, allowing us to trace the optimal path after computing the costs.
Continue reading Implementation of Multi-Stage Graph in Java

Implementation of All Pair Shortest Path Algorithm

In this post, we’ll walk through how to implement the All Pair Shortest Path algorithm in Java — a classic solution to find the shortest distances between every pair of vertices in a weighted graph.

What is the All Pair Shortest Path Problem?

The All Pair Shortest Path (APSP) problem involves finding the shortest distance between every possible pair of vertices in a graph. It’s commonly solved using Floyd-Warshall’s Algorithm, a dynamic programming approach that repeatedly updates the shortest distances between pairs of vertices by considering intermediate vertices.

How the Floyd-Warshall Algorithm Works

The core idea is to iteratively improve the estimate of the shortest path between any two vertices (i, j) by considering whether a path through a third vertex k would be shorter.

Here’s a breakdown:

  1. Initialize the adjacency matrix:
    • Set the distance between every vertex to infinity (or a large value like 32767 here), except for the diagonal, where the distance from a vertex to itself is 0.
  2. Input edges and their weights.
  3. Iteratively update shortest distances:
    • For each vertex k, update the distance between all pairs (i, j) as:
      g[i][j] = min(g[i][j], g[i][k] + g[k][j])
  4. After all iterations, the matrix g will hold the shortest distances between every pair.

Continue reading Implementation of All Pair Shortest Path Algorithm

Constructing The Minimum Spanning Tree for a Graph using Kruskal’s Algorithm

The Minimum Spanning Tree (MST) problem is a classic and fundamental topic in graph theory and algorithms. In this blog post, we will demonstrate how to implement Kruskal’s Algorithm in Java to construct a minimum spanning tree for a given graph.

What is a Minimum Spanning Tree?

A spanning tree of a graph is a subgraph that connects all the vertices together without any cycles and with the minimum possible number of edges (which is V-1 for a graph with V vertices).
A Minimum Spanning Tree (MST) is a spanning tree where the sum of the weights of the included edges is minimized.

How Kruskal’s Algorithm Works

Kruskal’s algorithm is a greedy algorithm that operates by always choosing the smallest available edge that connects two separate trees in the growing forest until a spanning tree is formed.

Here’s how it works:

  1. Sort all edges: Begin by sorting all the edges in non-decreasing order of their weights.
  2. Pick the smallest edge: Select the smallest edge and check if it forms a cycle with the spanning tree formed so far.
  3. If no cycle is formed, include it: Use a union-find (disjoint-set) structure to keep track of connected components and ensure no cycles are introduced.
  4. Repeat: Continue adding edges until there are V-1 edges in the spanning tree.
Continue reading Constructing The Minimum Spanning Tree for a Graph using Kruskal’s Algorithm

Constructing The Minimum Spanning Tree for a Graph using Prim’s Algorithm

The Minimum Spanning Tree (MST) problem is a fundamental topic in graph theory and algorithms. In this blog post, we demonstrate how to implement Prim’s Algorithm in Java to construct a minimum spanning tree for a given graph.

What is a Minimum Spanning Tree?

A spanning tree of a graph is a subgraph that includes all the vertices of the original graph connected by the minimum number of edges without forming any cycles. A minimum spanning tree is the one with the least total edge weight.

How Prim’s Algorithm Works?

Prim’s algorithm is a greedy algorithm that always chooses the smallest edge connecting a node in the MST to a node outside of it. Here’s how it works:

  1. Start from any vertex: Begin with any arbitrary vertex. This becomes part of the MST.
  2. Mark it as visited: Track which vertices are already included in the MST.
  3. Choose the smallest edge: From the visited nodes, pick the edge with the minimum weight that leads to an unvisited node.
  4. Add the new node and edge to MST: Include this new edge and the corresponding unvisited node in the MST.
  5. Repeat: Continue this process until all nodes are included.

At each step, the algorithm expands the MST by selecting the edge with the least possible weight, ensuring the tree grows optimally.

Continue reading Constructing The Minimum Spanning Tree for a Graph using Prim’s Algorithm

Implementing Greedy Knapsack Algorithm in Java

The Greedy Knapsack Problem/ Fractional Knapsack Problem is a classic example of a greedy algorithm. It differs from the 0/1 Knapsack Problem in that you are allowed to take fractions of an item rather than having to choose to take it or leave it entirely. In this blog post, we’ll walk through a Java implementation of the greedy approach to solving the fractional knapsack problem, explain how the logic works, and break down the sample output.

What is the Greedy Strategy for Knapsack?

In the greedy method, we aim to maximize the total profit by picking items with the highest profit-to-weight ratio. Here’s the approach:

  1. Calculate the profit-to-weight ratio for each item.
  2. Sort the items based on this ratio in descending order.
  3. Select items starting from the highest ratio until the knapsack is full:
    • If the item fits, include it completely.
    • If not, include as much of it as possible.
Continue reading Implementing Greedy Knapsack Algorithm in Java

Implementing Quicksort Algorithm in Java

Sorting is a fundamental operation in computer science, and QuickSort is one of the most popular and efficient sorting algorithms. In this blog post, we’ll look at a Java implementation of QuickSort, explain how it works, break down its steps with a sample output, and even visualize its working.

What is QuickSort?

QuickSort is a highly efficient, comparison-based, divide-and-conquer sorting algorithm. It was developed by Tony Hoare in 1959 and is widely used due to its performance on average-case scenarios.

How QuickSort Works:

  1. Divide: Select a pivot element from the array. Rearrange the array such that all elements less than the pivot go to its left, and all elements greater than the pivot go to its right.
  2. Conquer: Recursively apply the above step to the left and right subarrays.
  3. Combine: Since the array is sorted in-place, there’s no need for a combine step as in merge sort.
Continue reading Implementing Quicksort Algorithm in Java