<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Robin Viktorsson on Medium]]></title>
        <description><![CDATA[Stories by Robin Viktorsson on Medium]]></description>
        <link>https://medium.com/@robinviktorsson?source=rss-96f784843044------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FdHHxrWMHmI0Apv6</url>
            <title>Stories by Robin Viktorsson on Medium</title>
            <link>https://medium.com/@robinviktorsson?source=rss-96f784843044------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:48:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robinviktorsson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Model–View–ViewModel (MVVM) in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/model-view-viewmodel-mvvm-in-java-learn-with-practical-examples-53fbbe59e64f?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/53fbbe59e64f</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[model-view-viewmodel]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 17:47:27 GMT</pubDate>
            <atom:updated>2026-09-30T17:47:27.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA_oaf2yys7Gmgdi8z9zbQ.png" /></figure><p>As software applications become increasingly interactive, keeping the user interface synchronized with the application’s data becomes a significant challenge. Imagine a Java application where every time the application’s state changes, the developer must manually update labels, buttons, tables, and other user interface elements. Likewise, every user interaction must be translated into changes within the application’s business logic. As the application grows, this constant coordination quickly leads to tightly coupled code that is difficult to understand, test, and maintain.</p><p>To address this problem, software architects introduced the <em>Model–View–ViewModel (MVVM)</em> architectural pattern. Instead of allowing the user interface to communicate directly with the application’s business logic, MVVM introduces an additional component called the <em>ViewModel</em>. The Model continues to manage the application’s data and business rules, the View remains responsible for displaying information to the user, and the ViewModel acts as an intermediary that exposes the Model’s data in a form that is easy for the View to present. This separation allows the user interface to remain independent of the application’s underlying logic while making it much easier to keep the two synchronized.</p><p>The MVVM pattern was introduced by software architect <em>John Gossman</em> at Microsoft in 2005 as part of the development of <em>Windows Presentation Foundation (WPF)</em>. It was designed to take advantage of data binding, a feature that allows user interface elements to automatically reflect changes in application data without requiring developers to write large amounts of synchronization code. Although MVVM originated in the Microsoft ecosystem, its underlying principles have since been adopted by many modern user interface frameworks across desktop, web, and mobile development.</p><p>In Java, MVVM is most commonly associated with <em>JavaFX</em>, whose property binding and observable collections naturally support the pattern. Similar concepts also appear in Android development, reactive user interface frameworks, and many modern desktop applications. By separating presentation logic from both the View and the Model, MVVM makes applications easier to test, maintain, and extend while reducing the amount of code required to keep the user interface synchronized with the application’s state.</p><p>In this article, we’ll explore how Model–View–ViewModel works, discuss its advantages and limitations, build a complete Java implementation, and examine several practical examples that demonstrate why MVVM has become one of the most popular architectural patterns for modern user interface development.</p><h3>What is Model–View–ViewModel (MVVM)? 🤔</h3><p>Model–View–ViewModel (MVVM) is an architectural pattern designed to separate an application’s user interface from its business logic while making it easier to keep the two synchronized. Rather than allowing the View to manipulate the Model directly, MVVM introduces a fourth layer of abstraction called the <em>ViewModel</em>. The application is divided into three independent components: the Model, the View, and the ViewModel. Each component has a clearly defined responsibility and collaborates with the others to process user interactions and present application data.</p><p>When a user interacts with the application — for example, by clicking a button or entering text — the View forwards the action to the ViewModel. The ViewModel interprets the request, invokes the appropriate operations on the Model, and updates its own state based on the results. The View then displays the information exposed by the ViewModel. In many MVVM frameworks, this update happens automatically through <em>data binding</em>, allowing the user interface to remain synchronized with the application’s state without requiring the developer to manually refresh every UI element.</p><p>A simplified MVVM architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYp-3v-EwGeZKxlyrCyvIQ.png" /></figure><p>Although different frameworks implement MVVM in slightly different ways, the fundamental responsibilities remain the same. The <strong>View</strong> is responsible only for presenting information and capturing user interactions. It contains the application’s user interface but should not perform business logic or manipulate application data directly. In Java, the View might be implemented using JavaFX, Swing, a web page, or even a simple console interface.</p><p>The <em>ViewModel </em>acts as the intermediary between the View and the Model. It exposes the Model’s data in a form that is convenient for the View to display, processes user actions, performs presentation-specific logic, and invokes the appropriate business operations on the Model. Unlike a Controller in MVC, the ViewModel does not directly control or manipulate the View. Instead, it simply exposes data and operations, allowing the View to observe and display changes as they occur.</p><p>The <em>Model </em>represents the application’s data and business logic. It stores the application’s state, performs calculations, validates information, and enforces business rules. The Model remains completely independent of the user interface and has no knowledge of either the View or the ViewModel. Because of this separation, the same Model can often be reused by multiple applications or different user interfaces without modification.</p><p>One of the defining characteristics of MVVM is the separation between presentation and application logic through the ViewModel. Rather than manually updating the user interface after every change, the View simply reflects the state exposed by the ViewModel. This approach reduces coupling between components, simplifies testing, improves maintainability, and makes it easier to build responsive applications whose user interface stays synchronized with the underlying data as the application evolves.</p><h3>When Should You Use Model–View–ViewModel? 🧐</h3><p>Model–View–ViewModel is an excellent choice whenever an application has a rich, interactive user interface that must remain synchronized with its underlying data. Instead of requiring the View to manually retrieve and refresh information after every change, MVVM places a ViewModel between the View and the Model. The View simply displays the data exposed by the ViewModel, while the ViewModel manages presentation logic and communicates with the Model. This separation makes applications easier to understand, maintain, and test as they grow.</p><p>MVVM works particularly well for applications whose user interface changes frequently. Designers can modify the View without affecting the application’s business logic, while developers can enhance the Model without rewriting the user interface. Because presentation logic resides inside the ViewModel rather than the View itself, the application’s behavior can often be tested without launching the graphical interface, significantly simplifying automated testing.</p><p>Desktop applications are one of the most common use cases for MVVM. JavaFX naturally supports the pattern through properties, observable collections, and data binding. For example, a customer management application might display customer information in the View, expose formatted customer data through the ViewModel, and store customer records inside the Model. When the data changes, the View automatically reflects the latest state without requiring developers to manually update each user interface element.</p><p>MVVM is also well suited for applications that present dynamic or real-time information. Dashboards, monitoring systems, financial applications, inventory management systems, and media players often display data that changes continuously. By exposing observable data through the ViewModel, the interface can remain synchronized with the application’s state while keeping presentation logic separate from the underlying business rules.</p><p>Although MVVM is most closely associated with desktop development, its principles are equally valuable in modern mobile and web applications. Android applications have long adopted MVVM as one of their preferred architectural patterns, while many web frameworks implement similar concepts through reactive data binding. Regardless of the platform, the goal remains the same: keeping the user interface synchronized with application data while minimizing coupling between presentation and business logic.</p><p>In general, MVVM is most effective whenever an application requires a clear separation between user interface code, presentation logic, and business logic. If the same business rules may eventually support multiple user interfaces — such as a desktop application, a web application, and a mobile app — the Model can often be reused while each platform provides its own View and ViewModel.</p><p>For these reasons, MVVM has become one of the most popular architectural patterns for modern user interface development. Compared to MVC, it reduces the amount of code required to synchronize the user interface with application data, and compared to MVP, it places greater emphasis on declarative data binding rather than explicit communication between components. When combined with frameworks that support observable properties, MVVM provides a clean, maintainable, and highly testable foundation for building interactive Java applications.</p><h3>Limitations 📉</h3><p>Like every architectural pattern, Model–View–ViewModel involves trade-offs. While it provides an effective way to separate the user interface from an application’s business logic, it also introduces challenges that developers should consider before adopting it.</p><p>One of the most noticeable characteristics of MVVM is the increased number of components involved in even relatively simple features. Instead of placing presentation logic directly inside the user interface, developers create a separate ViewModel that communicates with the Model while exposing data to the View. This separation improves maintainability and testability, but it also increases the number of classes and interactions that developers must understand.</p><p>Another common challenge is that the ViewModel can gradually become too large. Because it is responsible for presentation logic, formatting data, handling user actions, and coordinating communication with the Model, it may accumulate responsibilities over time. Without careful design, a ViewModel can evolve into a “God ViewModel” containing hundreds or even thousands of lines of code, making it difficult to maintain and test. Breaking large ViewModels into smaller, feature-specific components often helps keep the architecture manageable.</p><p>MVVM can also introduce additional complexity for small applications. A simple utility or prototype may not benefit from separate Model, View, and ViewModel classes, especially if the application’s interface contains only a few screens. In these situations, the extra abstraction may outweigh its advantages, making a simpler architecture easier to implement and maintain.</p><p>Another limitation involves data binding itself. Although data binding greatly reduces the amount of code required to keep the user interface synchronized with application data, it can also make the application’s behavior less obvious. Changes to the Model may automatically propagate through the ViewModel and appear in the View without explicit method calls. While this produces cleaner code, it can sometimes make debugging more difficult because developers must understand the binding relationships rather than simply following a sequence of method invocations.</p><p>Finally, MVVM often depends on framework support to achieve its greatest benefits. Technologies such as JavaFX provide observable properties and binding mechanisms that make the pattern particularly effective. When these features are unavailable, developers may need to implement observer patterns, event listeners, or other synchronization mechanisms manually. Although MVVM can certainly be implemented using plain Java, doing so typically requires more boilerplate code than when using a framework with built-in data binding.</p><p>Despite these limitations, Model–View–ViewModel remains one of the most popular architectural patterns for modern user interface development. For applications with complex, interactive interfaces, its separation of concerns, improved testability, and support for automatic UI synchronization often outweigh the additional complexity. When implemented with clearly defined responsibilities and well-structured ViewModels, MVVM provides a flexible and maintainable foundation for building responsive Java applications.</p><h3>From Theory to Practice 🛠️</h3><p>Now that we understand how Model–View–ViewModel separates an application’s responsibilities, let’s see how it works in practice by building a simple Java application.</p><p>Imagine a user registering through an application. Rather than allowing the user interface to interact directly with the application’s business logic, the application is divided into three specialized components. The <em>View</em> is responsible for displaying information and capturing user interactions, the <em>ViewModel</em> processes those interactions while exposing data in a form that is easy for the View to present, and the <em>Model</em> stores the application’s data while applying its business rules. Instead of manually refreshing the user interface after every change, the View observes the ViewModel and updates automatically whenever the ViewModel’s state changes.</p><p>To keep the example simple, we’ll build a small user management application that allows users to be registered and displayed. Although intentionally minimal, it demonstrates the same collaboration between the Model, View, and ViewModel that appears in many desktop applications, mobile applications, and modern user interface frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUFBYItLB3HYs67HokNyTQ.png" /></figure><p>Our implementation consists of four classes. The <em>UserModel </em>represents the application’s data and business logic by storing registered users. The <em>UserViewModel</em> acts as the intermediary between the View and the Model. It receives user requests, invokes the appropriate business operations on the Model, and exposes the latest application state to the View. The <em>UserView</em> displays the information provided by the ViewModel and automatically refreshes whenever the ViewModel notifies it of a change. Finally, the <em>Main</em> class creates the application and simulates a user interacting with it.</p><p>Each class has a single, clearly defined responsibility. The View never modifies application data directly, the Model contains no user interface code, and the ViewModel contains presentation logic without knowing how the information is actually displayed. Notice that dependencies are provided through constructors rather than being created internally. This technique, known as <em>dependency injection</em>, reduces coupling and makes the components easier to test, replace, and reuse.</p><p>The following implementation demonstrates a complete MVVM application using plain Java, without relying on JavaFX or any external libraries. Instead of using framework-specific data binding, the example simulates automatic UI updates through a simple listener mechanism so that we can focus entirely on the architectural pattern itself.</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>// =========================<br>// Model<br>// =========================<br>class UserModel {<br><br>    // Stores all registered users<br>    private final List&lt;String&gt; users = new ArrayList&lt;&gt;();<br><br>    // Business logic for registering a user<br>    public void registerUser(String name) {<br><br>        // Validate the supplied name<br>        if (name == null || name.isBlank()) {<br>            throw new IllegalArgumentException(<br>                    &quot;User name cannot be empty.&quot;);<br>        }<br><br>        // Store the user<br>        users.add(name);<br>    }<br><br>    // Returns all registered users<br>    public List&lt;String&gt; getUsers() {<br>        return users;<br>    }<br>}<br><br>// =========================<br>// ViewModel<br>// =========================<br>class UserViewModel {<br><br>    private final UserModel model;<br><br>    // Listeners representing bound views<br>    private final List&lt;Runnable&gt; listeners =<br>            new ArrayList&lt;&gt;();<br><br>    UserViewModel(UserModel model) {<br>        this.model = model;<br>    }<br><br>    // Registers a listener (simulated data binding)<br>    public void addListener(Runnable listener) {<br>        listeners.add(listener);<br>    }<br><br>    // Registers a new user<br>    public void registerUser(String name) {<br><br>        // Update the model<br>        model.registerUser(name);<br><br>        // Notify all bound views<br>        notifyListeners();<br>    }<br><br>    // Exposes model data to the View<br>    public List&lt;String&gt; getUsers() {<br>        return model.getUsers();<br>    }<br><br>    // Notify every registered listener<br>    private void notifyListeners() {<br><br>        for (Runnable listener : listeners) {<br>            listener.run();<br>        }<br>    }<br>}<br><br>// =========================<br>// View<br>// =========================<br>class UserView {<br><br>    private final UserViewModel viewModel;<br><br>    UserView(UserViewModel viewModel) {<br><br>        this.viewModel = viewModel;<br><br>        // Subscribe to ViewModel updates<br>        viewModel.addListener(this::refresh);<br>    }<br><br>    // Refreshes the UI whenever data changes<br>    public void refresh() {<br><br>        System.out.println();<br>        System.out.println(&quot;Users:&quot;);<br><br>        for (String user : viewModel.getUsers()) {<br>            System.out.println(&quot;- &quot; + user);<br>        }<br>    }<br>}<br><br>// =========================<br>// Application Entry Point<br>// =========================<br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        // Create the MVVM components<br>        UserModel model = new UserModel();<br>        UserViewModel viewModel =<br>                new UserViewModel(model);<br>        UserView view =<br>                new UserView(viewModel);<br><br>        // Simulate user interaction<br>        viewModel.registerUser(&quot;Robin&quot;);<br>        viewModel.registerUser(&quot;Alice&quot;);<br>    }<br>}<br><br>// Output:<br>// Users:<br>// - Robin<br>// <br>// Users:<br>// - Robin<br>// - Alice</pre><p>After running the application, the interaction follows the same sequence that defines every MVVM application.</p><p>Suppose the user enters the name <em>Robin </em>and clicks <em>Register</em>. The request first reaches the <em>View</em>, which forwards the action to the <em>UserViewModel</em>. The ViewModel validates the request by delegating the business operation to the <em>UserModel</em>, which stores the new user and updates the application’s state. Once the operation has completed, the ViewModel notifies every registered View that its data has changed. The View then refreshes itself by requesting the latest information from the ViewModel and displaying it to the user.</p><p>Notice that each component focuses exclusively on its own responsibility. The <em>View </em>never stores users or performs business logic, the <em>Model </em>never interacts with the user interface, and the <em>ViewModel </em>exposes application data without knowing how it will be displayed. Unlike MVC, where the Controller explicitly tells the View what to display, the View simply observes the ViewModel and refreshes itself whenever the ViewModel’s state changes. This loose coupling is one of the defining characteristics of MVVM.</p><p>In a typical Java application, the View would often be implemented using <em>JavaFX</em>, where observable properties and data binding automatically synchronize the user interface with the ViewModel. Although our example uses a simple listener to simulate this behavior, the underlying principle is exactly the same: changes flow from the Model to the ViewModel, and the View automatically reflects the latest application state.</p><p>Although production systems are typically much larger and contain many more classes, the underlying idea remains exactly the same. Whether you’re building a desktop application, a mobile app, or another interactive user interface, MVVM provides a clean and maintainable way to separate presentation, presentation logic, and business logic while keeping the user interface synchronized with the application’s data.</p><h3>Practical Examples 💡</h3><p>Model–View–ViewModel is widely used in applications that require a responsive user interface while keeping presentation logic separate from business logic. Although the application domains vary, the collaboration between the components remains the same: the <em>View </em>displays information, the <em>ViewModel </em>exposes data and handles presentation logic, and the <em>Model </em>manages the application’s data and business rules.</p><p>The following examples use simple in-memory storage instead of databases or graphical user interfaces so that the code remains easy to understand and run. In production Java applications, the View would typically be implemented using JavaFX, where data binding automatically synchronizes the user interface with the ViewModel.</p><h4>1. Weather Dashboard</h4><p>Weather applications frequently display information that changes over time. The <em>Model </em>stores the latest weather measurements, the <em>ViewModel </em>formats the data for presentation, and the <em>View </em>automatically refreshes whenever new weather information becomes available. This keeps the user interface synchronized with changing conditions without requiring developers to manually update every display element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGBXI15y3mLrtU4LrRagyg.png" /></figure><p>Here is a simplified implementation:</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>// Model<br>class WeatherModel {<br><br>    private int temperature = 22;<br><br>    public int getTemperature() {<br>        return temperature;<br>    }<br><br>    public void setTemperature(int temperature) {<br>        this.temperature = temperature;<br>    }<br>}<br><br>// ViewModel<br>class WeatherViewModel {<br><br>    private final WeatherModel model;<br>    private final List&lt;Runnable&gt; listeners =<br>            new ArrayList&lt;&gt;();<br><br>    WeatherViewModel(WeatherModel model) {<br>        this.model = model;<br>    }<br><br>    public void addListener(Runnable listener) {<br>        listeners.add(listener);<br>    }<br><br>    public void updateTemperature(int temperature) {<br>        model.setTemperature(temperature);<br><br>        for (Runnable listener : listeners) {<br>            listener.run();<br>        }<br>    }<br><br>    public String getTemperatureText() {<br>        return model.getTemperature() + &quot;°C&quot;;<br>    }<br>}<br><br>// View<br>class WeatherView {<br><br>    WeatherView(WeatherViewModel viewModel) {<br><br>        viewModel.addListener(() -&gt;<br>                System.out.println(<br>                        &quot;Current Temperature: &quot;<br>                                + viewModel.getTemperatureText()));<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        WeatherModel model = new WeatherModel();<br>        WeatherViewModel viewModel =<br>                new WeatherViewModel(model);<br>        new WeatherView(viewModel);<br><br>        viewModel.updateTemperature(25);<br>        viewModel.updateTemperature(28);<br>    }<br>}<br><br>// Output:<br>// Current Temperature: 25°C<br>// Current Temperature: 28°C</pre><p>This example demonstrates one of MVVM’s greatest strengths. The View never reads data directly from the Model. Instead, it simply observes the ViewModel, which exposes the weather information in a format that is ready for display.</p><h4>2. Shopping Cart</h4><p>E-commerce applications constantly update totals, discounts, and item counts as customers add or remove products. The <em>Model</em> stores the shopping cart, the <em>ViewModel</em> calculates presentation-specific information such as the total price, and the <em>View</em> automatically refreshes whenever the cart changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMYuhfGAP5j9wsp91HtomA.png" /></figure><p>Here is a simplified implementation:</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>// Model<br>class ShoppingCartModel {<br><br>    private final List&lt;Double&gt; items =<br>            new ArrayList&lt;&gt;();<br><br>    public void addItem(double price) {<br>        items.add(price);<br>    }<br><br>    public List&lt;Double&gt; getItems() {<br>        return items;<br>    }<br>}<br><br>// ViewModel<br>class ShoppingCartViewModel {<br><br>    private final ShoppingCartModel model;<br>    private final List&lt;Runnable&gt; listeners =<br>            new ArrayList&lt;&gt;();<br><br>    ShoppingCartViewModel(ShoppingCartModel model) {<br>        this.model = model;<br>    }<br><br>    public void addListener(Runnable listener) {<br>        listeners.add(listener);<br>    }<br><br>    public void addItem(double price) {<br><br>        model.addItem(price);<br><br>        for (Runnable listener : listeners) {<br>            listener.run();<br>        }<br>    }<br><br>    public double getTotalPrice() {<br><br>        return model.getItems()<br>                .stream()<br>                .mapToDouble(Double::doubleValue)<br>                .sum();<br>    }<br>}<br><br>// View<br>class ShoppingCartView {<br><br>    ShoppingCartView(<br>            ShoppingCartViewModel viewModel) {<br><br>        viewModel.addListener(() -&gt;<br>                System.out.println(<br>                        &quot;Total: €&quot;<br>                                + viewModel.getTotalPrice()));<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        ShoppingCartModel model =<br>                new ShoppingCartModel();<br><br>        ShoppingCartViewModel viewModel =<br>                new ShoppingCartViewModel(model);<br><br>        new ShoppingCartView(viewModel);<br><br>        viewModel.addItem(19.99);<br>        viewModel.addItem(49.99);<br>    }<br>}<br><br>// Output:<br>// Total: €19.99<br>// Total: €69.98</pre><p>Notice that the calculation of the total price belongs entirely to the ViewModel. The Model simply stores the items, while the View only displays the formatted result.</p><h4>3. Music Player</h4><p>Music players provide another excellent example of MVVM. The <em>Model</em> stores playback information, the <em>ViewModel</em> exposes the current song and playback status, and the <em>View</em> automatically updates whenever the user starts a new track or pauses the music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fK5Yzdw7uYi6VBkZpA09Jg.png" /></figure><p>Here is a simplified implementation:</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>// Model<br>class MusicPlayerModel {<br><br>    private String currentSong = &quot;&quot;;<br><br>    public void playSong(String song) {<br>        currentSong = song;<br>    }<br><br>    public String getCurrentSong() {<br>        return currentSong;<br>    }<br>}<br><br>// ViewModel<br>class MusicPlayerViewModel {<br><br>    private final MusicPlayerModel model;<br><br>    private final List&lt;Runnable&gt; listeners =<br>            new ArrayList&lt;&gt;();<br><br>    MusicPlayerViewModel(<br>            MusicPlayerModel model) {<br><br>        this.model = model;<br>    }<br><br>    public void addListener(Runnable listener) {<br>        listeners.add(listener);<br>    }<br><br>    public void playSong(String song) {<br><br>        model.playSong(song);<br><br>        for (Runnable listener : listeners) {<br>            listener.run();<br>        }<br>    }<br><br>    public String getNowPlaying() {<br>        return &quot;Now Playing: &quot;<br>                + model.getCurrentSong();<br>    }<br>}<br><br>// View<br>class MusicPlayerView {<br><br>    MusicPlayerView(<br>            MusicPlayerViewModel viewModel) {<br><br>        viewModel.addListener(() -&gt;<br>                System.out.println(<br>                        viewModel.getNowPlaying()));<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        MusicPlayerModel model =<br>                new MusicPlayerModel();<br><br>        MusicPlayerViewModel viewModel =<br>                new MusicPlayerViewModel(model);<br><br>        new MusicPlayerView(viewModel);<br><br>        viewModel.playSong(&quot;Imagine&quot;);<br>        viewModel.playSong(&quot;Bohemian Rhapsody&quot;);<br>    }<br>}<br><br>// Output:<br>// Now Playing: Imagine<br>// Now Playing: Bohemian Rhapsody</pre><p>This example highlights how MVVM naturally supports dynamic user interfaces. Whenever the playback state changes, the ViewModel notifies the View, which immediately reflects the updated song information without containing any business logic itself.</p><p>Although these examples solve very different problems, they all follow the same architectural principle. The <em>View</em> presents information, the <em>ViewModel</em> exposes data and presentation logic, and the <em>Model</em> manages the application’s state and business rules. By keeping these responsibilities separate, Model–View–ViewModel makes applications easier to understand, test, maintain, and extend while allowing the user interface to remain synchronized with the underlying data.</p><h3>Conclusion 🎯</h3><p>Model–View–ViewModel has become one of the most influential architectural patterns for modern user interface development because it addresses a common challenge: keeping the user interface synchronized with an application’s data while maintaining a clear separation of responsibilities. By dividing an application into the <em>Model</em>, <em>View</em>, and <em>ViewModel</em>, developers can build software that is easier to understand, maintain, test, and extend as requirements evolve.</p><p>In this article, we explored how MVVM works, discussed its advantages and limitations, built a complete Java implementation, and examined several real-world examples, including a weather dashboard, a shopping cart, and a music player. Although these applications solve very different problems, they all follow the same architectural principle: the <em>Model</em> manages the application’s data and business logic, the <em>ViewModel</em> exposes that data in a form suitable for presentation, and the <em>View</em> displays it while automatically reflecting changes in the application’s state.</p><p>MVVM has become particularly popular in frameworks that support data binding and observable state. JavaFX naturally embraces the pattern through its property binding APIs, while similar concepts are widely used in Android development and many modern reactive UI frameworks. By moving presentation logic into the ViewModel and reducing direct coupling between the View and the Model, MVVM makes it easier to build responsive applications with highly interactive user interfaces.</p><p>For Java developers, MVVM offers a clean and maintainable way to organize applications that contain complex user interfaces. Because the ViewModel can be tested independently of the View, automated testing becomes significantly simpler, while the Model remains reusable across different platforms and interfaces. This separation allows applications to evolve over time without tightly coupling business logic to presentation code.</p><p>Whether you’re building a desktop application, a mobile app, a dashboard, or another interactive system, Model–View–ViewModel provides a flexible and scalable architecture for organizing your code. By understanding MVVM and how it differs from patterns such as MVC and MVP, you’ll be better equipped to design modern Java applications that remain maintainable, testable, and responsive as they continue to grow.</p><p>Thanks for reading! If you found this article helpful, consider giving it a clap and following me for more articles on software engineering, algorithms, and software architecture. 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53fbbe59e64f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prim’s Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/prims-algorithm-in-java-learn-with-practical-examples-5decd6dd9c2e?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/5decd6dd9c2e</guid>
            <category><![CDATA[prims-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 12:18:02 GMT</pubDate>
            <atom:updated>2026-09-10T12:18:02.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSY4p4WQpdeTcPTRJH2kqQ.png" /></figure><p>Many real-world networks need to connect a set of locations while keeping construction or maintenance costs as low as possible. Whether you’re designing a telecommunications network, laying electrical cables, building roads, or planning water distribution systems, the challenge is often the same: connect everything using the least amount of resources.</p><p>In graph theory, this problem can be modeled using a <em>Minimum Spanning Tree (MST)</em>. Given a weighted, undirected graph, a Minimum Spanning Tree connects every vertex without creating cycles while minimizing the total weight of the selected edges. In other words, it produces the cheapest possible network that still keeps every vertex connected.</p><p>One of the most important algorithms for finding a Minimum Spanning Tree is <em>Prim’s Algorithm</em>. Developed by Czech mathematician <a href="https://en.wikipedia.org/wiki/Vojt%C4%9Bch_Jarn%C3%ADk">Vojtěch Jarník </a>in 1930 and later rediscovered by <a href="https://en.wikipedia.org/wiki/Robert_C._Prim">Robert Prim</a> and <a href="https://en.wikipedia.org/wiki/Edsger_W._Dijkstra">Edsger Dijkstra</a>, it remains one of the most widely taught greedy algorithms in computer science.</p><p>Prim’s Algorithm builds a Minimum Spanning Tree incrementally. Starting from a single vertex, it repeatedly selects the lowest-cost edge that connects a vertex already in the tree to a vertex outside it. By continuing this process until every vertex has been included, the algorithm constructs an MST with the smallest possible total weight.</p><p>Because it grows outward from a starting point, Prim’s Algorithm is particularly well suited to scenarios where a network expands gradually, such as connecting cities, offices, routers, substations, or other facilities. Its simplicity, efficiency, and practical relevance have made it a cornerstone topic in graph theory, algorithms, and software engineering courses.</p><p>In this article, we’ll explore how Prim’s Algorithm works, examine the greedy strategy behind it, implement it step by step in Java, discuss the Priority Queue data structure that powers its efficiency, and work through practical examples that demonstrate where and why it is useful.</p><h3>What Is Prim’s Algorithm? 🔍</h3><p>Prim’s Algorithm is a greedy algorithm used to find a Minimum Spanning Tree (MST) in a weighted, undirected graph. A spanning tree is a subset of edges that:</p><ul><li>Connects every vertex in the graph</li><li>Contains no cycles</li><li>Uses exactly <em>V − 1</em> edges (V = number of vertices)</li></ul><p>In simple terms, an MST connects every node in the graph while keeping the overall cost as low as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*bPrLVbAQXdYwej22jSQQPQ.gif" /><figcaption>Animation of Prim’s algorithm. <a href="https://commons.wikimedia.org/wiki/File:PrimAlgDemo.gif">Shiyu Ji</a>, <a href="https://creativecommons.org/licenses/by-sa/4.0">CC BY-SA 4.0</a>, via Wikimedia Commons</figcaption></figure><p>Unlike e.g. Kruskal’s Algorithm, which considers all edges globally and builds the tree by choosing the cheapest edges across the entire graph, Prim’s Algorithm grows a single tree from a chosen starting vertex. At each step, it selects the cheapest edge that connects the existing tree to a new vertex. This makes Prim’s Algorithm feel more like an expanding wave that spreads through the graph one connected region at a time.</p><p>The process is straightforward:</p><ol><li>Choose any starting vertex.</li><li>Mark it as part of the MST.</li><li>Find the cheapest edge connecting the MST to an unvisited vertex.</li><li>Add that edge and vertex to the MST.</li><li>Repeat until all vertices are included.</li></ol><p>Because the algorithm always chooses the lowest-cost valid connection available at each step, it follows the greedy approach.</p><p>A useful way to visualize Prim’s Algorithm is to imagine building a road network from a single city. Starting from one city, we repeatedly build the cheapest road that reaches a city not yet connected to our growing network. Over time, the network expands outward until every city becomes connected. The same idea applies to laying cables between offices, connecting substations in a power grid, or linking routers in a communication backbone.</p><p>By always selecting the cheapest expansion, Prim’s Algorithm guarantees a Minimum Spanning Tree with the smallest possible total weight.</p><h3>When Should You Use Prim’s Algorithm? 🧐</h3><p>Prim’s Algorithm is designed to solve the Minimum Spanning Tree (MST) problem — selecting a subset of edges that connects all vertices while minimizing total edge weight and avoiding cycles.</p><p>It is most useful when your goal is not to find the shortest route between two points, but to connect an entire set of points as cheaply as possible. In other words, Prim’s Algorithm is the right choice when you want to build a network, not navigate through one. Common applications include:</p><ul><li>Road network construction</li><li>Electrical power grid design</li><li>Computer network infrastructure</li><li>Water distribution systems</li><li>Telecommunications backbone networks</li><li>Pipeline and utility planning</li><li>Sensor and communication network layout</li></ul><p>In each of these scenarios, the goal is to connect every location while minimizing infrastructure costs. For example, a city planner may want to connect several neighborhoods with the least expensive road system possible. A telecom company may want to connect data centers and offices using the cheapest cable layout. An electrical engineer may want to design a transmission network that reaches every substation without unnecessary wiring.</p><p>Prim’s Algorithm is particularly effective when working with dense graphs, where the number of edges is relatively large. Because it expands from one vertex outward and repeatedly chooses the cheapest edge that crosses the boundary of the current tree, it performs very well when many possible connections exist. When implemented with an adjacency list and a Priority Queue, it runs in <em>O(E log V)</em><strong> </strong>where:</p><ul><li>V = number of vertices</li><li>E = number of edges</li></ul><p>The Priority Queue efficiently selects the next cheapest edge that expands the tree. This makes Prim’s Algorithm a strong choice when the graph is large and the cost of repeatedly scanning all edges would be too high.</p><p>The space complexity is <em>O(V + E) </em>because the algorithm stores the graph structure, visited vertices, and Priority Queue contents.</p><p>Prim’s Algorithm is often the best option when:</p><ul><li>The graph is connected or can be treated as connected</li><li>You want to grow the MST from a specific starting point</li><li>The graph has many edges</li><li>The graph is stored as an adjacency list</li><li>You need an efficient MST solution for infrastructure-style problems</li></ul><p>Prim’s Algorithm is not always the easiest or fastest choice in such situations:</p><ul><li>If your graph is already represented as an edge list, Kruskal’s Algorithm may be simpler.</li><li>If the graph is sparse and edge sorting is convenient, Kruskal’s Algorithm can be a better fit.</li><li>If you need shortest paths instead of a minimum spanning tree, you should use Dijkstra’s, Bellman-Ford, or Floyd-Warshall instead.</li></ul><p>So, Prim’s Algorithm is best used when the problem is about connecting everything with minimum total cost, especially when the graph is dense and the network grows naturally from one starting point.</p><h3>Limitations of Prim’s Algorithm 📉</h3><p>As already mentioned, although Prim’s Algorithm is highly efficient, it is not the ideal solution for every graph problem.</p><h4>1. Requires a Connected Graph</h4><p>Prim’s Algorithm assumes the graph is connected. If the graph contains multiple disconnected components, a single Minimum Spanning Tree cannot be produced. In that case, you would need to run the algorithm separately on each component or use a different approach depending on the problem.</p><h4>2. Priority Queue Overhead</h4><p>Efficient implementations rely on a Priority Queue (Min Heap). While highly effective, maintaining the heap introduces additional complexity compared to simpler graph traversals. This overhead is worth it for large graphs, but it may be unnecessary for very small inputs.</p><h4>3. Less Natural for Edge-Based Data</h4><p>Prim’s Algorithm performs best when graphs are represented using adjacency lists. If data is already stored as an edge list, Kruskal’s Algorithm is often simpler to implement because it works directly with edges and sorting.</p><h4>4. Does Not Solve Shortest-Path Problems</h4><p>A Minimum Spanning Tree minimizes the total weight of the entire network, not the shortest distance between specific vertices. For example:</p><ul><li>Dijkstra’s Algorithm finds shortest paths from a source vertex.</li><li>Bellman-Ford Algorithm supports negative weights.</li><li>Floyd-Warshall Algorithm computes all-pairs shortest paths.</li><li>Prim’s Algorithm constructs a Minimum Spanning Tree.</li></ul><p>Using Prim’s Algorithm when shortest paths are required can produce incorrect solutions.</p><h4>5. The Starting Vertex Can Affect Build Order</h4><p>Prim’s Algorithm can start from any vertex in a connected graph, and the total MST weight will remain the same. However, the order in which vertices and edges are added may differ depending on the starting point. This matters in implementations where you want to trace the algorithm step by step or visualize how the tree grows.</p><p>Despite these limitations, Prim’s Algorithm remains one of the most efficient and practical MST algorithms available.</p><h3>From Theory to Practice 🛠️</h3><p>Unlike Kruskal’s Algorithm, which focuses on sorting edges, Prim’s Algorithm grows a tree vertex by vertex.</p><p>Because the algorithm repeatedly examines neighboring vertices, an adjacency list is usually the most natural graph representation. This is especially true in real-world systems where each location or device is connected only to a limited set of nearby or relevant neighbors. The algorithm maintains:182368</p><ul><li>A set of visited vertices</li><li>A Priority Queue containing candidate edges</li><li>The growing Minimum Spanning Tree</li></ul><p>At each step, the cheapest edge leaving the current tree is selected and added to the MST. This makes Prim’s Algorithm particularly useful in applications where the network expands outward from a central point or where the cheapest next connection must always be chosen from the current frontier.</p><h4>1. Prim’s Algorithm Implementation</h4><p>Before looking at the code, it helps to understand what this implementation 182368is doing. The Java example below uses an <em>adjacency list</em> to represent the graph, a PriorityQueue to always select the cheapest available edge, and a visited array to ensure each vertex is added to the Minimum Spanning Tree only once.</p><p>Starting from vertex 0, the algorithm gradually builds the Minimum Spanning Tree. At each step, it selects the lowest-weight edge that connects a vertex already in the tree to a vertex that has not yet been visited. This greedy strategy ensures the tree stays connected while keeping the total weight minimal.</p><pre>import java.util.*;<br><br>// Represents a weighted edge in the graph<br>class Edge {<br>    int destination; // The node this edge points to<br>    int weight;      // Cost of traveling this edge<br><br>    Edge(int destination, int weight) {<br>        this.destination = destination;<br>        this.weight = weight;<br>    }<br>}<br><br>public class Main {<br><br>    // Prim&#39;s Algorithm implementation to compute MST<br>    public static void prim(List&lt;List&lt;Edge&gt;&gt; graph, int vertices) {<br><br>        // Tracks whether a vertex is already included in the MST<br>        boolean[] visited = new boolean[vertices];<br><br>        // Min-heap priority queue:<br>        // stores {vertex, edgeWeight}, always extracts smallest weight first<br>        PriorityQueue&lt;int[]&gt; pq =<br>            new PriorityQueue&lt;&gt;(Comparator.comparingInt(a -&gt; a[1]));<br><br>        // Start MST from vertex 0 with cost 0<br>        pq.offer(new int[]{0, 0});<br><br>        int totalWeight = 0; // Accumulates total cost of MST edges<br><br>        System.out.println(&quot;Minimum Spanning Tree:&quot;);<br><br>        // Continue until all reachable vertices are processed<br>        while (!pq.isEmpty()) {<br><br>            // Extract the edge with the smallest weight<br>            int[] current = pq.poll();<br>            int vertex = current[0]; // current node<br>            int weight = current[1];  // cost to reach it<br><br>            // Skip if already included in MST (prevents cycles)<br>            if (visited[vertex]) {<br>                continue;<br>            }<br><br>            // Mark this vertex as part of MST<br>            visited[vertex] = true;<br><br>            // Add its connection cost to total MST weight<br>            totalWeight += weight;<br><br>            // Print step-by-step MST construction<br>            System.out.println(&quot;Vertex &quot; + vertex +<br>                               &quot; added with edge weight &quot; + weight);<br><br>            // Explore all adjacent edges of current vertex<br>            for (Edge edge : graph.get(vertex)) {<br><br>                // Only consider edges leading to unvisited vertices<br>                if (!visited[edge.destination]) {<br><br>                    // Add candidate edge to priority queue<br>                    pq.offer(new int[]{<br>                        edge.destination,<br>                        edge.weight<br>                    });<br>                }<br>            }<br>        }<br><br>        // Final MST cost output<br>        System.out.println(&quot;Total Weight: &quot; + totalWeight);<br>    }<br><br>    public static void main(String[] args) {<br><br>        int vertices = 4; // Number of nodes in the graph<br><br>        // Adjacency list representation of the graph<br>        List&lt;List&lt;Edge&gt;&gt; graph = new ArrayList&lt;&gt;();<br><br>        // Initialize adjacency list for each vertex<br>        for (int i = 0; i &lt; vertices; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        // Add undirected weighted edges (bidirectional connections)<br><br>        graph.get(0).add(new Edge(1, 10)); // Edge 0 -&gt; 1<br>        graph.get(1).add(new Edge(0, 10)); // Edge 1 -&gt; 0<br><br>        graph.get(0).add(new Edge(2, 6));  // Edge 0 -&gt; 2<br>        graph.get(2).add(new Edge(0, 6));  // Edge 2 -&gt; 0<br><br>        graph.get(0).add(new Edge(3, 5));  // Edge 0 -&gt; 3<br>        graph.get(3).add(new Edge(0, 5));  // Edge 3 -&gt; 0<br><br>        graph.get(1).add(new Edge(3, 15)); // Edge 1 -&gt; 3<br>        graph.get(3).add(new Edge(1, 15)); // Edge 3 -&gt; 1<br><br>        graph.get(2).add(new Edge(3, 4));  // Edge 2 -&gt; 3 (cheapest link)<br>        graph.get(3).add(new Edge(2, 4));  // Edge 3 -&gt; 2<br><br>        // Run Prim&#39;s algorithm to compute MST<br>        prim(graph, vertices);<br>    }<br>}<br><br>// Output:<br>// Minimum Spanning Tree:<br>// Vertex 0 added with edge weight 0<br>// Vertex 3 added with edge weight 5<br>// Vertex 2 added with edge weight 4<br>// Vertex 1 added with edge weight 10<br>// Total Weight: 19</pre><p>The implementation begins by initializing a visited array to track which vertices have already been included in the MST. A PriorityQueue (used as a min-heap) ensures that the smallest available edge is always processed first.</p><p>The algorithm starts at vertex 0, pushing it into the queue with weight 0. In each iteration, it extracts the cheapest candidate edge. If the target vertex is already visited, it is skipped. Otherwise, the vertex is added to the MST, its weight contributes to the total cost, and all outgoing edges to unvisited vertices are pushed into the queue.</p><p>Because the priority queue continuously maintains candidate edges sorted by weight, the algorithm never needs to scan the entire graph to find the next best choice. It simply expands the tree step by step until all vertices are included, producing a Minimum Spanning Tree with minimum total weight.</p><h4>2. Representing Graphs with Adjacency Lists</h4><p>Because Prim’s Algorithm frequently examines neighboring vertices, adjacency lists provide efficient access to outgoing edges. Each vertex stores a list of adjacent vertices and the corresponding edge weights.</p><p>This allows the algorithm to quickly discover candidate edges while expanding the tree. In practical terms, this is useful when each node only connects to a small number of nearby nodes, such as cities connected by roads or routers connected by network links.</p><h4>3. Understanding the Priority Queue</h4><p>The Priority Queue is the heart of Prim’s Algorithm. At any moment, the queue contains all edges that could potentially expand the current tree. Whenever a new vertex is added:</p><ul><li>Its outgoing edges are inserted into the queue.</li><li>The cheapest edge is extracted.</li><li>If it leads to an unvisited vertex, it becomes part of the MST.</li></ul><p>This ensures the algorithm always selects the lowest-cost expansion available. In real-world use, this means Prim’s Algorithm is constantly evaluating the cheapest next step in building a network. That is why it works so well for infrastructure planning and other cost-sensitive connection problems.</p><h4>4. Growing the Minimum Spanning Tree</h4><p>Unlike Kruskal’s Algorithm, which merges disconnected components, Prim’s Algorithm maintains a single connected tree throughout execution.</p><p>The MST grows outward one vertex at a time until every vertex becomes part of the tree. This growth pattern is especially useful when the network naturally expands from a central hub. For example, a company may begin with one headquarters and gradually connect branch offices, or a utility provider may extend service from one substation to surrounding areas.</p><h4>5. Why Priority Queues Improve Performance</h4><p>Without a Priority Queue, the algorithm would repeatedly scan all available edges to find the cheapest candidate. A Min Heap allows this operation to be performed efficiently, reducing the overall running time to <em>O(E log V)</em>.</p><p>This efficiency is one of the main reasons Prim’s Algorithm is widely used in practice. It allows large graphs to be processed without checking every possible edge at every step.</p><h4>6. Object-Oriented Implementation</h4><p>For simplicity, the earlier implementation keeps everything inside a single class. This is useful for learning because it shows all components of the algorithm in one place without unnecessary abstraction.</p><p>In real-world applications, however, a more object-oriented design is preferred. The graph structure and the algorithm logic are usually separated into different classes. A Graph class is responsible for storing vertices and edges, while a PrimMST class handles the Minimum Spanning Tree construction.</p><p>This separation improves readability, makes the code easier to maintain, and allows the algorithm to be reused in different contexts such as network simulation, graph visualization, infrastructure planning, or performance analysis.</p><pre>import java.util.*;<br><br>// Represents an edge in the graph<br>class Edge {<br>    int destination;<br>    int weight;<br><br>    Edge(int destination, int weight) {<br>        this.destination = destination;<br>        this.weight = weight;<br>    }<br>}<br><br>// Graph class responsible for storing vertices and edges<br>class Graph {<br>    int vertices;<br>    List&lt;List&lt;Edge&gt;&gt; adjacencyList;<br><br>    Graph(int vertices) {<br>        this.vertices = vertices;<br>        this.adjacencyList = new ArrayList&lt;&gt;();<br><br>        for (int i = 0; i &lt; vertices; i++) {<br>            adjacencyList.add(new ArrayList&lt;&gt;());<br>        }<br>    }<br><br>    // Add an undirected weighted edge<br>    void addEdge(int source, int destination, int weight) {<br>        adjacencyList.get(source)<br>                     .add(new Edge(destination, weight));<br><br>        adjacencyList.get(destination)<br>                     .add(new Edge(source, weight));<br>    }<br>}<br><br>// Prim&#39;s Algorithm implementation class<br>class PrimMST {<br><br>    void runPrim(Graph graph) {<br><br>        boolean[] visited =<br>            new boolean[graph.vertices];<br><br>        PriorityQueue&lt;int[]&gt; pq =<br>            new PriorityQueue&lt;&gt;(<br>                Comparator.comparingInt(a -&gt; a[1])<br>            );<br><br>        // Start from vertex 0<br>        pq.offer(new int[]{0, 0});<br><br>        int totalWeight = 0;<br><br>        System.out.println(&quot;Minimum Spanning Tree:&quot;);<br><br>        while (!pq.isEmpty()) {<br><br>            int[] current = pq.poll();<br><br>            int vertex = current[0];<br>            int weight = current[1];<br><br>            if (visited[vertex]) {<br>                continue;<br>            }<br><br>            visited[vertex] = true;<br>            totalWeight += weight;<br><br>            System.out.println(<br>                &quot;Vertex &quot; + vertex +<br>                &quot; added with edge weight &quot; +<br>                weight<br>            );<br><br>            for (Edge edge :<br>                graph.adjacencyList.get(vertex)) {<br><br>                if (!visited[edge.destination]) {<br><br>                    pq.offer(<br>                        new int[]{<br>                            edge.destination,<br>                            edge.weight<br>                        }<br>                    );<br>                }<br>            }<br>        }<br><br>        System.out.println(<br>            &quot;Total Weight: &quot; + totalWeight<br>        );<br>    }<br>}<br><br>// Main class to run the program<br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        // Create graph with 4 vertices<br>        Graph graph = new Graph(4);<br><br>        // Add weighted edges<br>        graph.addEdge(0, 1, 10);<br>        graph.addEdge(0, 2, 6);<br>        graph.addEdge(0, 3, 5);<br>        graph.addEdge(1, 3, 15);<br>        graph.addEdge(2, 3, 4);<br><br>        // Run Prim&#39;s Algorithm<br>        new PrimMST().runPrim(graph);<br>    }<br>}<br><br>// Output:<br>// Minimum Spanning Tree:<br>// Vertex 0 added with edge weight 0<br>// Vertex 3 added with edge weight 5<br>// Vertex 2 added with edge weight 4<br>// Vertex 1 added with edge weight 10<br>// Total Weight: 19</pre><p>This object-oriented version separates concerns clearly. The Graph class is responsible only for storing the graph structure, while the PrimMST class focuses entirely on the algorithm itself. This makes the code easier to extend and maintain as applications grow larger.</p><p>Despite the structural change, the algorithm remains exactly the same. A Priority Queue is used to repeatedly select the cheapest edge that expands the current tree, and vertices are marked as visited to ensure that cycles are never introduced. The process continues until all vertices have been added to the Minimum Spanning Tree.</p><h3>Practical Examples 💡</h3><p>Prim’s Algorithm is widely used whenever a network needs to be expanded from an existing starting point while keeping total costs as low as possible. Because the algorithm grows outward one vertex at a time, it naturally fits many real-world infrastructure and optimization problems. Below are three practical examples that demonstrate how it can be applied.</p><h4>1. Procedural Dungeon Generation in Games</h4><p>Prim’s Algorithm is commonly used in procedural content generation, particularly for creating dungeon layouts in games. Rooms can be represented as vertices, while possible corridors between rooms become weighted edges.</p><p>The goal is to connect every room while avoiding unnecessary loops and minimizing the total number of corridors. This produces a dungeon that is fully explorable while remaining efficient and easy to navigate.</p><p>Many roguelikes, puzzle games, and adventure games use Minimum Spanning Trees as a foundation for generating maps before optionally adding a few extra connections to create alternative routes.</p><pre>// Create a graph representing rooms in a dungeon<br>Graph graph = new Graph(6);<br><br>// Weight = corridor construction cost or distance<br>// between rooms<br><br>graph.addEdge(0, 1, 4); // Corridor between Room 0 and Room 1<br>graph.addEdge(0, 2, 3); // Short corridor<br>graph.addEdge(1, 2, 1); // Cheapest connection<br>graph.addEdge(1, 3, 5); // Longer hallway<br>graph.addEdge(2, 4, 6); // Distant room connection<br>graph.addEdge(3, 4, 2); // Efficient route<br>graph.addEdge(3, 5, 7); // Boss room path<br>graph.addEdge(4, 5, 3); // Alternative route<br><br>// Generate the dungeon backbone<br>new PrimMST().runPrim(graph);<br><br>// Output:<br>// Minimum Spanning Tree:<br>// Vertex 0 added with edge weight 0<br>// Vertex 2 added with edge weight 3<br>// Vertex 1 added with edge weight 1<br>// Vertex 3 added with edge weight 5<br>// Vertex 4 added with edge weight 2<br>// Vertex 5 added with edge weight 3<br>// Total Weight: 14</pre><p>The resulting Minimum Spanning Tree creates a dungeon where every room can be reached while using the minimum number of corridors necessary to maintain connectivity. Game developers often start with this structure and then add a few extra corridors afterward to create loops, shortcuts, and alternative exploration paths.</p><h4>2. Water Distribution Network</h4><p>One common application of Prim’s Algorithm is designing a water distribution system. Reservoirs, pumping stations, and distribution hubs can be represented as vertices, while possible pipeline connections become weighted edges. The weight of each edge represents the cost of installing and maintaining a pipeline.</p><p>Rather than building every possible connection, engineers want to connect all locations using the minimum amount of pipe and construction cost. Prim’s Algorithm helps identify the cheapest network that still delivers water to every location.</p><pre>// Create a graph representing water facilities<br>Graph graph = new Graph(5);<br><br>// Each edge represents a possible pipeline<br>// Weight = installation cost of the pipeline<br><br>graph.addEdge(0, 1, 3); // Low-cost pipeline<br>graph.addEdge(0, 2, 8); // Long-distance connection<br>graph.addEdge(1, 2, 2); // Cheapest connection<br>graph.addEdge(1, 3, 5); // Medium-cost pipeline<br>graph.addEdge(2, 4, 7); // Expensive route<br>graph.addEdge(3, 4, 4); // Alternative connection<br><br>// Build the cheapest water distribution network<br>new PrimMST().runPrim(graph);<br><br>// Output:<br>// Minimum Spanning Tree:<br>// Vertex 0 added with edge weight 0<br>// Vertex 1 added with edge weight 3<br>// Vertex 2 added with edge weight 2<br>// Vertex 3 added with edge weight 5<br>// Vertex 4 added with edge weight 4<br>// Total Weight: 14</pre><p>The resulting Minimum Spanning Tree connects every facility while minimizing total pipeline construction cost.</p><h4>3. Wireless Sensor Network Deployment</h4><p>Wireless sensor networks are commonly used in agriculture, environmental monitoring, smart cities, and industrial automation. Each sensor can be modeled as a vertex, while possible communication links between sensors become weighted edges.</p><p>The weight of each edge may represent installation cost, signal loss, power consumption, or communication expense. Prim’s Algorithm can determine the most efficient communication backbone connecting all sensors.</p><pre>// Create a graph representing wireless sensors<br>Graph graph = new Graph(6);<br><br>// Weight = communication or installation cost<br><br>graph.addEdge(0, 1, 1); // Nearby sensors<br>graph.addEdge(0, 2, 4); // Longer communication link<br>graph.addEdge(1, 2, 2); // Efficient connection<br>graph.addEdge(1, 3, 5); // Medium-cost link<br>graph.addEdge(2, 4, 3); // Good connection<br>graph.addEdge(3, 5, 4); // Sensor expansion<br>graph.addEdge(4, 5, 2); // Low-cost communication path<br><br>// Build the minimum-cost sensor network<br>new PrimMST().runPrim(graph);<br><br>// Output:<br>// Minimum Spanning Tree:<br>// Vertex 0 added with edge weight 0<br>// Vertex 1 added with edge weight 1<br>// Vertex 2 added with edge weight 2<br>// Vertex 4 added with edge weight 3<br>// Vertex 5 added with edge weight 2<br>// Vertex 3 added with edge weight 4<br>// Total Weight: 12</pre><p>This produces a communication structure that connects all sensors while minimizing deployment and operating costs.</p><p>Prim’s Algorithm is one of the most elegant examples of a greedy graph algorithm. By starting from a single vertex and repeatedly selecting the cheapest edge that expands the current tree, it efficiently constructs a Minimum Spanning Tree with the lowest possible total weight.</p><p>Its combination of simplicity, efficiency, and practical relevance makes it a cornerstone topic in graph theory and software engineering. When paired with an adjacency list and Priority Queue, Prim’s Algorithm performs exceptionally well, particularly on dense graphs where many connections exist between vertices.</p><p>Like Kruskal’s Algorithm, Prim’s Algorithm is not designed for shortest-path problems. Its purpose is to minimize the total cost of an entire network rather than optimize routes between individual vertices.</p><p>From road systems and telecommunications to electrical grids and infrastructure planning, Prim’s Algorithm demonstrates how a simple greedy strategy can solve complex optimization problems efficiently. More than ninety years after its original discovery, it remains one of the most important and widely used algorithms in computer science.</p><h3>Conclusion 📣</h3><p>Prim’s Algorithm is a powerful and practical greedy approach for solving the Minimum Spanning Tree problem, enabling efficient design of cost-optimized networks in both theoretical and real-world settings. By incrementally expanding from a starting vertex and always selecting the lowest-cost edge that connects the growing tree to a new vertex, it guarantees a globally optimal solution for connecting all nodes without cycles while minimizing total edge weight.</p><p>Through its Java implementations and practical examples, it becomes clear that Prim’s Algorithm is not just an abstract graph theory concept, but a highly applicable tool in areas such as infrastructure planning, telecommunications, water distribution systems, and procedural game content generation. Its reliance on adjacency lists and priority queues allows it to scale effectively to large and dense graphs, making it suitable for real-world engineering problems where efficiency matters.</p><p>While it has some limitations — such as requiring a connected graph and not being suited for shortest-path problems — its strengths in building minimal-cost connected networks make it a foundational algorithm in computer science. Understanding Prim’s Algorithm not only deepens one’s grasp of greedy strategies and graph theory but also provides a practical method for solving a wide range of optimization challenges in software engineering and system design.</p><p>Thanks for reading! Please give this article a clap and follow me if you enjoyed it 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5decd6dd9c2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Floyd–Warshall Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/floyd-warshall-algorithm-in-java-learn-with-practical-examples-2cda18e1bd8f?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cda18e1bd8f</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[floyd-warshall]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 12:01:01 GMT</pubDate>
            <atom:updated>2026-06-15T12:01:01.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROSa2XwJtgfxkjkPcg-C_g.png" /></figure><p>Floyd–Warshall is one of the most important shortest-path algorithms in computer science. Unlike algorithms such as <a href="https://medium.com/@robinviktorsson/dijkstras-algorithm-in-java-learn-with-practical-examples-9e7af310e466">Dijkstra’s</a> or <a href="https://medium.com/@robinviktorsson/bellman-ford-algorithm-in-java-learn-with-practical-examples-9442f7392cec">Bellman–Ford</a>, which compute shortest paths from <em>a single source vertex</em>, Floyd–Warshall computes the shortest path between <em>every pair of vertices</em> in a weighted graph.</p><p>Because many real-world systems require distances between all locations rather than just one starting point, Floyd–Warshall is widely used in transportation networks, routing systems, social network analysis, geographic information systems, and graph optimization problems.</p><p>The algorithm was independently developed by <a href="https://en.wikipedia.org/wiki/Robert_W._Floyd">Robert Floyd</a> and <a href="https://en.wikipedia.org/wiki/Stephen_Warshall">Stephen Warshall</a> during the 1960s. It remains one of the most elegant examples of dynamic programming and is considered a foundational algorithm in graph theory.</p><p>At its core, Floyd–Warshall repeatedly considers whether introducing an intermediate vertex can improve the currently known shortest path between two vertices. By systematically evaluating every possible intermediate vertex, the algorithm gradually refines all shortest-path distances until the optimal solution is obtained.</p><p>In this article, we’ll break down how Floyd–Warshall works, implement it step by step in Java, explore negative cycle detection, and examine practical examples that demonstrate where and why it is useful.</p><h3>What Is Floyd–Warshall? 🔍</h3><p>Floyd–Warshall finds the shortest path between <em>every pair of vertices</em> in a weighted graph.</p><p>A weighted graph is a graph where each connection (edge) has an associated value such as distance, cost, travel time, profit, or latency. The goal is to determine the minimum accumulated weight between every possible pair of vertices.</p><p>The algorithm works as follows:</p><ul><li>Create a distance matrix</li><li>Set the distance from each vertex to itself as 0</li><li>Set direct edge weights in the matrix</li><li>Initialize all missing connections as ∞ (infinity)</li><li>Consider each vertex as a potential intermediate vertex</li><li>Update distances whenever a shorter path is discovered through that intermediate vertex</li></ul><p>Where:</p><ul><li>V = number of vertices</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DmnCyZJlGEijDBRQ.png" /><figcaption>Floyd-Warshall example. <a href="https://commons.wikimedia.org/w/index.php?curid=23230210">By Dcoetzee — Own work</a></figcaption></figure><p>For every pair of vertices (i, j), Floyd–Warshall asks: <em>“Would traveling through vertex k produce a shorter path?”. </em>If so, update the distance.</p><p>Unlike the related Bellman–Ford algorithm, which repeatedly relaxes edges, Floyd–Warshall gradually improves an entire distance matrix until all shortest paths are known.</p><p>A useful way to visualize the algorithm is to imagine progressively allowing more vertices to participate as intermediate stops. Each iteration introduces one additional vertex that paths may pass through. By the end, every possible intermediate combination has been considered.</p><h3>When Should You Use Floyd–Warshall? 🧐</h3><p>Floyd–Warshall is specifically designed for situations where shortest paths are required between <em>all pairs of vertices</em>. Common applications include:</p><ul><li>Road-network analysis</li><li>Airline route planning</li><li>Social network analysis</li><li>Network latency optimization</li><li>Geographic information systems (GIS)</li></ul><p>Unlike Dijkstra’s algorithm, which computes shortest paths from a <em>single source vertex</em> and must be run once per vertex to obtain all-pairs shortest paths, Floyd–Warshall computes the shortest distances between <em>every pair of vertices in a single execution</em>.</p><p>It achieves this by maintaining a distance matrix where each entry dist[i][j] represents the currently known shortest distance from vertex i to vertex j. The algorithm then repeatedly checks whether allowing another vertex k to act as an intermediate point produces a shorter path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*kYdL_yhL8CK6vxthzumr5w.png" /></figure><p>By applying this update for every combination of vertices (i, j, k), Floyd–Warshall systematically considers all possible intermediate vertices and gradually improves the distance matrix until it contains the shortest-path distance between every pair of vertices. This dynamic-programming approach is what allows the algorithm to solve the all-pairs shortest-path problem in a single run, rather than repeatedly executing a single-source algorithm.</p><p>Another important feature is its ability to work with <em>negative edge weights</em>, provided that no negative-weight cycles exist. In fact, Floyd–Warshall can also be used to detect negative cycles: if any diagonal entry in the final distance matrix becomes negative (dist[i][i] &lt; 0), a negative-weight cycle is present.</p><p>The algorithm runs with a time complexity of <em>O(V³)</em>, where:</p><ul><li>V = number of vertices</li></ul><p>Its space complexity is <em>O(V²)</em> because it stores a distance matrix containing distances between every pair of vertices.</p><p>Because of its cubic running time, Floyd–Warshall is typically best suited for small to medium-sized dense graphs or situations where all-pairs shortest-path information is needed repeatedly after a single pre-processing step. For very large sparse graphs, running Dijkstra’s algorithm from each vertex is often more efficient.</p><h3>Limitations of Floyd–Warshall 📉</h3><p>Although Floyd–Warshall is elegant and relatively simple to implement, it also has several important limitations that should be considered when choosing a shortest-path algorithm.</p><h4><strong>1. Computationally Expensive</strong></h4><p>Floyd–Warshall performs three nested iterations over all vertices in the graph, resulting in a time complexity of <em>O(V³)</em>. As the number of vertices increases, the amount of work grows very quickly. For example:</p><ul><li>100 vertices → approximately 1 million operations</li><li>1,000 vertices → approximately 1 billion operations</li><li>10,000 vertices → approximately 1 trillion operations</li></ul><p>This rapid growth makes Floyd–Warshall impractical for very large graphs, especially when real-time or near real-time results are required.</p><h4><strong>2. High Memory Usage</strong></h4><p>The algorithm stores a <em>V × V distance matrix</em> that contains the shortest known distance between every pair of vertices. This requires <em>O(V²)</em> memory. While this is manageable for small graphs, memory consumption grows significantly as the number of vertices increases. For example:</p><ul><li>1,000 vertices require a matrix with 1 million entries.</li><li>10,000 vertices require a matrix with 100 million entries.</li></ul><p>In large-scale systems, such as social networks or internet routing infrastructures, storing the entire matrix may become prohibitively expensive.</p><h4><strong>3. Less Suitable for Sparse Graphs</strong></h4><p>Floyd–Warshall processes every possible pair of vertices regardless of how many edges actually exist. In sparse graphs, where the number of edges is much smaller than the maximum possible number of edges, much of this computation is unnecessary. Algorithms such as Edsger W. Dijkstra can often exploit sparsity and achieve significantly better performance.</p><p>For this reason, Floyd–Warshall is generally most attractive for dense graphs, where many vertex pairs are directly or indirectly connected and the all-pairs distance matrix is genuinely useful.</p><h4><strong>4. Negative Cycles Prevent Valid Solutions</strong></h4><p>One advantage of Floyd–Warshall is its ability to handle negative edge weights, something many shortest-path algorithms cannot do. However, the algorithm cannot produce meaningful shortest-path distances when a negative-weight cycle exists. A negative cycle is a loop whose total weight is less than zero.</p><p>For example, consider a cycle with total weight −5. A path could traverse that cycle repeatedly:</p><pre>A → B → C → A → B → C → ...</pre><p>Each traversal reduces the total path cost by another 5 units. Since the path cost can decrease indefinitely, there is no well-defined “shortest” path.</p><p>Floyd–Warshall can detect such situations by examining the final distance matrix. If any diagonal entry becomes negative (dist[i][i] &lt; 0), a negative cycle is reachable from that vertex.</p><p>Despite these limitations, Floyd–Warshall remains one of the most widely taught and widely used all-pairs shortest-path algorithms. Its concise dynamic-programming formulation, ability to handle negative edge weights, and straightforward implementation make it an excellent choice for small to medium-sized graphs, dense networks, and applications where shortest-path information is needed between many or all pairs of vertices.</p><h3>From Theory to Practice 🛠️</h3><p>Now that we understand the theory behind Floyd–Warshall, let’s see how the algorithm can be implemented in Java.</p><p>Unlike e.g. Bellman–Ford, which focuses on finding shortest paths from a single source and therefore works efficiently with an edge list, Floyd–Warshall computes the shortest paths between every pair of vertices. To do this, the algorithm repeatedly asks: <em>“Can the path from vertex </em><em>i to vertex </em><em>j be improved by passing through an intermediate vertex </em><em>k?&quot;</em></p><p>Since this calculation must be performed for every pair (i, j), an <em>adjacency matrix</em> (more precisely, a distance matrix) is the most natural representation. Each cell dist[i][j] stores the shortest known distance from vertex i to vertex j, allowing the algorithm to update distances efficiently as it considers each intermediate vertex.</p><p>As the algorithm progresses, this matrix is gradually refined until it contains the shortest distances between all pairs of vertices.</p><h4>1. Floyd–Warshall Graph Implementation</h4><p>Let’s start with a complete Java implementation of the Floyd–Warshall algorithm. The program represents the graph as an adjacency matrix, where each cell contains either the weight of an edge or INF if no direct connection exists between two vertices.</p><p>The algorithm begins by copying this matrix into a distance matrix. It then systematically considers each vertex as a potential intermediate stop between every source and destination pair. Whenever traveling through that intermediate vertex produces a shorter path, the distance matrix is updated.</p><p>By the time all vertices have been evaluated, the distance matrix contains the shortest-path distances between every pair of vertices in the graph.</p><pre>import java.util.Arrays;<br><br>public class Main {<br><br>    // A large value used to represent &quot;no direct path&quot;<br>    static final int INF = 999999;<br><br>    public static void floydWarshall(int[][] graph) {<br><br>        // Number of vertices in the graph<br>        int vertices = graph.length;<br><br>        // Distance matrix that will store the shortest<br>        // known distances between every pair of vertices<br>        int[][] dist = new int[vertices][vertices];<br><br>        // Initialize the distance matrix with the<br>        // original edge weights from the graph<br>        for (int i = 0; i &lt; vertices; i++) {<br>            dist[i] = Arrays.copyOf(<br>                    graph[i],<br>                    vertices<br>            );<br>        }<br><br>        // Core idea:<br>        // If the shortest path from i to j passes through<br>        // an intermediate vertex k, then its length is:<br>        //<br>        // dist[i][k] + dist[k][j]<br>        //<br>        // If this route is shorter than the currently<br>        // known distance dist[i][j], update it.<br><br>        // Try every vertex k as an intermediate vertex<br>        for (int k = 0; k &lt; vertices; k++) {<br><br>            // Consider every possible source vertex i<br>            for (int i = 0; i &lt; vertices; i++) {<br><br>                // Consider every possible destination vertex j<br>                for (int j = 0; j &lt; vertices; j++) {<br><br>                    // Ensure both subpaths exist and<br>                    // check whether going through k<br>                    // produces a shorter path<br>                    if (dist[i][k] != INF &amp;&amp;<br>                        dist[k][j] != INF &amp;&amp;<br>                        dist[i][k] + dist[k][j]<br>                                &lt; dist[i][j]) {<br><br>                        // Update the shortest known distance<br>                        dist[i][j] =<br>                                dist[i][k]<br>                                + dist[k][j];<br>                    }<br>                }<br>            }<br>        }<br><br>        // Print the final all-pairs shortest-path matrix<br>        System.out.println(<br>                &quot;Shortest-path matrix:&quot;<br>        );<br><br>        for (int[] row : dist) {<br>            System.out.println(<br>                    Arrays.toString(row)<br>            );<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Adjacency matrix representation:<br>        // graph[i][j] = weight of edge i -&gt; j<br>        // INF means there is no direct edge<br>        int[][] graph = {<br>                {0,   3,   INF, 7},<br>                {8,   0,   2,   INF},<br>                {5,   INF, 0,   1},<br>                {2,   INF, INF, 0}<br>        };<br><br>        // Compute shortest paths between all pairs of vertices<br>        floydWarshall(graph);<br>    }<br>}<br><br>// Output:<br>// Shortest-path matrix:<br>// [0, 3, 5, 6]<br>// [5, 0, 2, 3]<br>// [3, 6, 0, 1]<br>// [2, 5, 7, 0]</pre><p>This implementation showcases the three fundamental stages of the Floyd–Warshall algorithm:</p><ul><li><strong>Distance matrix initialization</strong> copies the graph’s edge weights into a working matrix.</li><li><strong>Intermediate-vertex evaluation</strong> considers each vertex as a possible waypoint between all pairs of vertices.</li><li><strong>Shortest-path relaxation</strong> updates distances whenever a shorter path is discovered through an intermediate vertex.</li></ul><p>After the algorithm completes, the resulting matrix contains the shortest distances between every pair of vertices, making Floyd–Warshall one of the most elegant solutions to the all-pairs shortest path problem.</p><h4>2. Understanding the Dynamic Programming Update</h4><p>The core of the Floyd–Warshall algorithm is a dynamic programming recurrence. For each intermediate vertex k, the algorithm asks a simple question: “<em>Is the path from </em><em>i to </em><em>j shorter if we travel through </em><em>k?”</em></p><p>This idea is implemented with the following update:</p><pre>if (dist[i][k] + dist[k][j]<br>        &lt; dist[i][j]) {<br>    dist[i][j] =<br>            dist[i][k]<br>            + dist[k][j];<br>}</pre><p>For example, suppose we know:</p><ul><li>A → B = 4</li><li>B → C = 3</li><li>A → C = 10</li></ul><p>When considering B as an intermediate vertex, the algorithm discovers an alternative route from A to C:</p><pre>A → B → C = 4 + 3 = 7</pre><p>Since 7 is less than the current distance of 10, the algorithm updates the distance from A to C to 7.</p><p>This update is performed for every pair of vertices (i, j) and every possible intermediate vertex k. By repeatedly refining the distance matrix in this way, the algorithm gradually uncovers the shortest paths between all pairs of vertices.</p><h4>3. Negative Cycle Detection</h4><p>Floyd–Warshall can also detect negative-weight cycles by examining the diagonal entries of the distance matrix after the algorithm completes:</p><pre>for (int i = 0; i &lt; vertices; i++) {<br>    if (dist[i][i] &lt; 0) {<br>        System.out.println(<br>                &quot;Negative cycle detected!&quot;<br>        );<br>        return;<br>    }<br>}</pre><p>Initially, every diagonal entry dist[i][i] is 0 because the cost of traveling from a vertex to itself is zero. During the algorithm, distances are updated whenever a shorter path is discovered.</p><p>If a negative-weight cycle is reachable from vertex i, the algorithm will eventually find a path that starts at i, traverses the cycle, and returns to i with a total cost less than zero. As a result, dist[i][i] becomes negative.</p><p>Therefore, after all updates are complete:</p><ul><li>dist[i][i] == 0 means no negative cycle has affected vertex i.</li><li>dist[i][i] &lt; 0 indicates that a negative-weight cycle is reachable from vertex i.</li></ul><p>A negative value on the diagonal is a clear signal that the graph contains a negative-weight cycle and that some shortest paths are undefined, since repeatedly traversing the cycle can reduce the path cost indefinitely.</p><h4>4. Path Reconstruction</h4><p>In many real-world applications, knowing only the shortest distance is not enough — we also need to reconstruct the actual path between two vertices. The Floyd–Warshall algorithm can be extended to support this by maintaining an additional <em>next matrix</em>. We define:</p><pre>int[][] next = new int[vertices][vertices];</pre><p>The purpose of next[i][j] is to store the <em>next vertex to visit</em> when moving from vertex i to vertex j along the currently known shortest path. In other words, it acts as a routing table that tells us the first step to take from i toward j.</p><p>Whenever a shorter path from i to j is found via an intermediate vertex k, we update both the distance and the path information:</p><pre>dist[i][j] = dist[i][k] + dist[k][j];<br>next[i][j] = next[i][k];</pre><p>The distance update records the new shortest path length, while the next update ensures that the routing information follows the same path structure.</p><p>After the algorithm finishes, the next matrix can be used to reconstruct the full shortest path between any two vertices. Starting from the source vertex, we repeatedly follow the entries stored in next until the destination is reached.</p><p>The following complete example computes all-pairs shortest paths and reconstructs the shortest route from vertex 0 to vertex 2.</p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>public class Main {<br><br>    static final int INF = 999999;<br><br>    public static void floydWarshall(int[][] graph) {<br><br>        int vertices = graph.length;<br><br>        int[][] dist = new int[vertices][vertices];<br>        int[][] next = new int[vertices][vertices];<br><br>        // Initialize distance and next matrices<br>        for (int i = 0; i &lt; vertices; i++) {<br>            for (int j = 0; j &lt; vertices; j++) {<br><br>                dist[i][j] = graph[i][j];<br><br>                if (i == j) {<br>                    next[i][j] = i;<br>                }<br>                else if (graph[i][j] != INF) {<br>                    next[i][j] = j;<br>                }<br>                else {<br>                    next[i][j] = -1;<br>                }<br>            }<br>        }<br><br>        // Floyd–Warshall algorithm<br>        for (int k = 0; k &lt; vertices; k++) {<br>            for (int i = 0; i &lt; vertices; i++) {<br>                for (int j = 0; j &lt; vertices; j++) {<br><br>                    if (dist[i][k] != INF &amp;&amp;<br>                        dist[k][j] != INF &amp;&amp;<br>                        dist[i][k] + dist[k][j] &lt; dist[i][j]) {<br><br>                        dist[i][j] =<br>                                dist[i][k] + dist[k][j];<br><br>                        next[i][j] =<br>                                next[i][k];<br>                    }<br>                }<br>            }<br>        }<br><br>        // Print shortest-path matrix<br>        System.out.println(&quot;Shortest-path matrix:&quot;);<br><br>        for (int[] row : dist) {<br>            System.out.println(Arrays.toString(row));<br>        }<br><br>        // Example: reconstruct path from 0 to 2<br>        List&lt;Integer&gt; path =<br>                reconstructPath(0, 2, next);<br><br>        System.out.println(<br>                &quot;\nShortest path from 0 to 2: &quot;<br>                + path<br>        );<br><br>        System.out.println(<br>                &quot;Distance: &quot;<br>                + dist[0][2]<br>        );<br>    }<br><br>    public static List&lt;Integer&gt; reconstructPath(<br>            int start,<br>            int end,<br>            int[][] next) {<br><br>        List&lt;Integer&gt; path = new ArrayList&lt;&gt;();<br><br>        if (next[start][end] == -1) {<br>            return path;<br>        }<br><br>        int current = start;<br>        path.add(current);<br><br>        while (current != end) {<br>            current = next[current][end];<br>            path.add(current);<br>        }<br><br>        return path;<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[][] graph = {<br>                {0,   3,   INF, 7},<br>                {8,   0,   2,   INF},<br>                {5,   INF, 0,   1},<br>                {2,   INF, INF, 0}<br>        };<br><br>        floydWarshall(graph);<br>    }<br>}<br><br>// Output:<br>// Shortest-path matrix:<br>// [0, 3, 5, 6]<br>// [5, 0, 2, 3]<br>// [3, 6, 0, 1]<br>// [2, 5, 7, 0]<br><br>// Shortest path from 0 to 2: [0, 1, 2]<br>// Distance: 5</pre><p>By maintaining the next matrix alongside the distance matrix, the Floyd–Warshall algorithm becomes more than a shortest-distance algorithm. It can also return the exact sequence of vertices that forms each shortest path, making it useful for routing systems, network analysis, navigation software, and many other practical applications.</p><h4>5. Object-Oriented Implementation</h4><p>The Floyd–Warshall algorithm can be cleanly implemented using an object-oriented approach in Java. In this design, the Graph class encapsulates the adjacency matrix and provides methods for constructing the graph and computing shortest paths between all pairs of vertices.</p><p>This structure makes the algorithm easier to manage, reuse, and extend, especially when working with larger or more complex graph-based systems.</p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>class Graph {<br><br>    // A large constant used to represent the absence of a direct edge<br>    static final int INF = 999999;<br><br>    private final int vertices;<br>    private final int[][] matrix;<br><br>    // Stores shortest distances after Floyd–Warshall<br>    private int[][] dist;<br><br>    // Stores path reconstruction information<br>    private int[][] next;<br><br>    // Initializes the graph with INF values and 0 on the diagonal<br>    public Graph(int vertices) {<br>        this.vertices = vertices;<br>        matrix = new int[vertices][vertices];<br><br>        for (int i = 0; i &lt; vertices; i++) {<br>            Arrays.fill(matrix[i], INF);<br>            matrix[i][i] = 0;<br>        }<br>    }<br><br>    // Adds a directed weighted edge to the graph<br>    public void addEdge(int source, int destination, int weight) {<br>        matrix[source][destination] = weight;<br>    }<br><br>    // Computes shortest paths between all pairs using Floyd–Warshall<br>    public void floydWarshall() {<br><br>        dist = new int[vertices][vertices];<br>        next = new int[vertices][vertices];<br><br>        // Initialize distance and path matrices<br>        for (int i = 0; i &lt; vertices; i++) {<br>            for (int j = 0; j &lt; vertices; j++) {<br><br>                dist[i][j] = matrix[i][j];<br><br>                if (i == j) {<br>                    next[i][j] = i;<br>                }<br>                else if (matrix[i][j] != INF) {<br>                    next[i][j] = j;<br>                }<br>                else {<br>                    next[i][j] = -1;<br>                }<br>            }<br>        }<br><br>        // Floyd–Warshall algorithm<br>        for (int k = 0; k &lt; vertices; k++) {<br>            for (int i = 0; i &lt; vertices; i++) {<br>                for (int j = 0; j &lt; vertices; j++) {<br><br>                    if (dist[i][k] != INF &amp;&amp;<br>                        dist[k][j] != INF &amp;&amp;<br>                        dist[i][k] + dist[k][j] &lt; dist[i][j]) {<br><br>                        dist[i][j] =<br>                                dist[i][k] + dist[k][j];<br><br>                        // Update path information<br>                        next[i][j] = next[i][k];<br>                    }<br>                }<br>            }<br>        }<br><br>        // Print shortest-path matrix<br>        System.out.println(&quot;Shortest-path matrix:&quot;);<br><br>        for (int[] row : dist) {<br>            System.out.println(Arrays.toString(row));<br>        }<br>    }<br><br>    // Reconstructs the shortest path between two vertices<br>    public List&lt;Integer&gt; getPath(int start, int end) {<br><br>        if (next == null) {<br>            throw new IllegalStateException(<br>                    &quot;Run floydWarshall() first.&quot;<br>            );<br>        }<br><br>        List&lt;Integer&gt; path = new ArrayList&lt;&gt;();<br><br>        if (next[start][end] == -1) {<br>            return path;<br>        }<br><br>        int current = start;<br>        path.add(current);<br><br>        while (current != end) {<br>            current = next[current][end];<br>            path.add(current);<br>        }<br><br>        return path;<br>    }<br><br>    // Returns the shortest distance between two vertices<br>    public int getDistance(int start, int end) {<br><br>        if (dist == null) {<br>            throw new IllegalStateException(<br>                    &quot;Run floydWarshall() first.&quot;<br>            );<br>        }<br><br>        return dist[start][end];<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        Graph graph = new Graph(4);<br><br>        graph.addEdge(0, 1, 3);<br>        graph.addEdge(0, 3, 7);<br><br>        graph.addEdge(1, 0, 8);<br>        graph.addEdge(1, 2, 2);<br><br>        graph.addEdge(2, 0, 5);<br>        graph.addEdge(2, 3, 1);<br><br>        graph.addEdge(3, 0, 2);<br><br>        graph.floydWarshall();<br><br>        System.out.println(<br>                &quot;\nShortest path from 0 to 2: &quot;<br>                + graph.getPath(0, 2)<br>        );<br><br>        System.out.println(<br>                &quot;Distance: &quot;<br>                + graph.getDistance(0, 2)<br>        );<br>    }<br>}<br><br>// Output:<br>// Shortest-path matrix:<br>// [0, 3, 5, 6]<br>// [5, 0, 2, 3]<br>// [3, 6, 0, 1]<br>// [2, 5, 7, 0]<br><br>// Shortest path from 0 to 2: [0, 1, 2]<br>// Distance: 5</pre><p>This implementation demonstrates how the Floyd–Warshall algorithm can be structured in a clean and modular way using object-oriented principles. The adjacency matrix serves as the core data representation, while the algorithm operates on a separate working copy to compute shortest paths without modifying the original graph.</p><p>By combining simplicity with clear separation of responsibilities, this approach provides a solid foundation for further enhancements such as path reconstruction, support for undirected graphs, or integration into larger graph-processing systems.</p><h3>Practical Examples 💡</h3><p>The Floyd–Warshall algorithm is widely used in systems where we need to compute shortest paths between every pair of nodes in a network. Unlike single-source algorithms (such as Dijkstra), which compute paths from one starting point, Floyd–Warshall produces a complete all-pairs shortest path table. This makes it especially useful in applications where:</p><ul><li>The same network is queried repeatedly</li><li>Fast response time is important after pre-processing</li><li>Relationships between <em>all</em> entities matter, not just one</li></ul><p>Although the algorithm itself runs in <em>O(n3)O(n³)O(n3)</em>, its real advantage is that once it finishes, any distance query can be answered in constant time <em>O(1)</em>.</p><p>Below are some practical real-world use cases.</p><h4>1. Airline Route Planning</h4><p>Airline networks are a classic example of a weighted graph. In this model:</p><ul><li><em>Airports</em> are represented as vertices.</li><li><em>Direct flights</em> are represented as edges.</li><li>Edge weights can represent <em>distance, flight duration, fuel consumption,</em> or <em>operating cost.</em></li></ul><p>Airlines often need to determine the most efficient route between any two airports in their network. Because passengers may travel between thousands of origin–destination pairs, computing shortest paths on demand can be expensive. Floyd–Warshall solves this problem by precomputing the optimal route between <em>every pair of airports</em> in a single execution.</p><pre>Graph airline = new Graph(4);<br><br>// Direct flight routes between airports<br>airline.addEdge(0, 1, 500);   // Airport 0 → 1<br>airline.addEdge(1, 2, 300);   // Airport 1 → 2<br>airline.addEdge(2, 3, 250);   // Airport 2 → 3<br>airline.addEdge(0, 3, 1500);  // Direct but expensive route<br><br>// Compute all-pairs shortest paths<br>airline.floydWarshall();<br><br>System.out.println(<br>        &quot;\nShortest path from 0 to 3: &quot;<br>        + airline.getPath(0, 3)<br>);<br><br>System.out.println(<br>        &quot;Distance: &quot;<br>        + airline.getDistance(0, 3)<br>);<br><br>// Output:<br>// Shortest-path matrix:<br>// [0, 500, 800, 1050]<br>// [999999, 0, 300, 550]<br>// [999999, 999999, 0, 250]<br>// [999999, 999999, 999999, 0]<br><br>// Shortest path from 0 to 3: [0, 1, 2, 3]<br>// Distance: 1050</pre><p>At first glance, the direct flight from Airport 0 to Airport 3 appears to be the obvious choice because it requires only one flight. However, Floyd–Warshall evaluates all possible intermediate airports and discovers a cheaper route:</p><pre>0 → 1 → 2 → 3<br><br>Total cost:<br>500 + 300 + 250 = 1050</pre><p>This is significantly less expensive than the direct route: 0 -&gt; 3 = 1500<em>. </em>As a result, the algorithm updates the shortest distance between Airports 0 and 3 from 1500 to 1050.</p><h4>2. Social Network Analysis</h4><p>Social networks such as messaging platforms, professional networking sites, and online communities can be modeled as graphs:</p><ul><li><em>Users </em>are represented as vertices.</li><li><em>Friendships, follows, or connections </em>are represented as edges.</li><li>Edge weights can represent the <em>strength of a relationship, interaction frequency</em>, or simply the number of steps required to reach another user.</li></ul><p>One common problem in social network analysis is determining how closely two users are connected. Even if two users are not directly linked, they may still be connected through mutual friends or intermediate contacts.</p><p>Floyd–Warshall helps solve this problem by computing the shortest connection path between <em>every pair of users</em> in the network.</p><pre>Graph social = new Graph(5);<br><br>// Friendship connections<br>social.addEdge(0, 1, 1);<br>social.addEdge(1, 2, 1);<br>social.addEdge(2, 3, 1);<br>social.addEdge(3, 4, 1);<br>social.addEdge(0, 4, 10);<br><br>// Compute all-pairs shortest paths<br>social.floydWarshall();<br><br>// Output:<br>// Shortest-path matrix:<br>// [0, 1, 2, 3, 4]<br>// [999999, 0, 1, 2, 3]<br>// [999999, 999999, 0, 1, 2]<br>// [999999, 999999, 999999, 0, 1]<br>// [999999, 999999, 999999, 999999, 0]<br><br>// Shortest path from 0 to 4: [0, 1, 2, 3, 4]<br>// Distance: 4</pre><p>At first, User 0 appears to have a direct connection to User 4 with a distance of 10. However, Floyd–Warshall evaluates all possible intermediate users and discovers a much shorter path:</p><pre>0 → 1 → 2 → 3 → 4<br><br>Total distance:<br>1 + 1 + 1 + 1 = 4</pre><p>Since 4 &lt; 10, the algorithm updates the shortest distance between Users 0 and 4 from 10 to 4.</p><p>This reveals that although the users are not strongly connected directly, they are relatively close through a chain of mutual connections.</p><h4>3. Transportation Systems</h4><p>Modern transportation networks consist of many interconnected locations, including train stations, bus stops, airports, and transit hubs. These networks can be naturally modeled as weighted graphs:</p><ul><li><em>Vertices </em>represent stations, stops, or terminals.</li><li><em>Edges </em>represent direct routes between locations.</li><li>Edge weights typically represent <em>travel time, distance, ticket cost, or expected transit delay</em>.</li></ul><p>Transportation planners and navigation systems frequently need to answer questions such as:</p><ul><li><em>What is the fastest route between two stations?</em></li><li><em>How long will a journey take?</em></li><li><em>Which transfer combination minimizes travel time?</em></li></ul><p>Rather than calculating routes from scratch every time a query is made, Floyd–Warshall can precompute the shortest travel times between <em>all pairs of locations</em> in a single execution.</p><pre>Graph transport = new Graph(4);<br><br>// Travel times between stations<br>transport.addEdge(0, 1, 10);  // Station 0 → 1<br>transport.addEdge(1, 2, 15);  // Station 1 → 2<br>transport.addEdge(0, 3, 50);  // Direct but slower route<br>transport.addEdge(2, 3, 10);  // Station 2 → 3<br><br>// Compute all-pairs shortest travel times<br>transport.floydWarshall();<br><br>// Output:<br>// Shortest-path matrix:<br>// [0, 10, 25, 35]<br>// [999999, 0, 15, 25]<br>// [999999, 999999, 0, 10]<br>// [999999, 999999, 999999, 0]<br><br>// Shortest path from 0 to 3: [0, 1, 2, 3]<br>// Distance: 35</pre><p>The direct route from Station 0<em> t</em>o Station 3 takes 50 minutes.</p><pre>0 → 3 = 50</pre><p>However, Floyd–Warshall evaluates alternative routes through intermediate stations and discovers a faster journey:</p><pre>0 → 1 → 2 → 3<br><br>Total travel time:<br>10 + 15 + 10 = 35</pre><p>Since 35 minutes is shorter than 50 minutes, the algorithm updates the shortest travel time between Stations 0 and 3.</p><h3>Conclusion 📣</h3><p>Floyd–Warshall is one of the most elegant and versatile shortest-path algorithms in graph theory. By using a dynamic programming approach, it efficiently computes the shortest distance between every pair of vertices in a weighted graph, making it fundamentally different from single-source algorithms such as Dijkstra’s or Bellman–Ford.</p><p>Throughout this article, we explored how the algorithm works, examined its core distance-update recurrence, implemented it in Java, added support for path reconstruction, and extended the solution using object-oriented design principles. We also saw how Floyd–Warshall can detect negative-weight cycles and how it can be applied to practical problems such as airline route planning, social network analysis, and transportation systems.</p><p>The algorithm’s greatest strength is its ability to provide complete all-pairs shortest-path information after a single pre-processing step. Once the distance matrix has been computed, shortest-path queries can be answered instantly, making Floyd–Warshall particularly valuable in applications where the same network is queried repeatedly.</p><p>However, this convenience comes at a cost. With a time complexity of <em>O(V³)</em> and a space complexity of <em>O(V²)</em>, Floyd–Warshall is best suited for small to medium-sized graphs, dense networks, and scenarios where all-pairs shortest-path information is required. For very large or sparse graphs, algorithms such as Dijkstra’s often provide better scalability.</p><p>Despite being developed more than half a century ago, Floyd–Warshall remains a cornerstone of graph algorithms and an excellent example of dynamic programming in practice. Its concise implementation, support for negative edge weights, ability to reconstruct shortest paths, and applicability across a wide range of real-world problems ensure that it continues to be an essential tool in every software engineer’s and computer scientist’s toolkit.</p><p>Whether you’re building a routing engine, analyzing network connectivity, optimizing transportation systems, or simply learning graph algorithms, understanding Floyd–Warshall provides valuable insight into one of the most influential algorithms in computer science.</p><p>Thanks for reading! Please give this article a clap and follow me if you enjoyed it 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cda18e1bd8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bellman–Ford Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/bellman-ford-algorithm-in-java-learn-with-practical-examples-9442f7392cec?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/9442f7392cec</guid>
            <category><![CDATA[bellman-ford-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 16:22:14 GMT</pubDate>
            <atom:updated>2026-06-14T05:00:23.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8arSDSo7qYbbg0RceeIg1A.png" /></figure><p>Bellman–Ford is one of the most important shortest-path algorithms in computer science. It computes the minimum-cost path between nodes in a weighted graph and is particularly valuable because it can correctly handle graphs that contain negative edge weights.</p><p>Because many real-world optimization problems involve costs that may increase or decrease over time, Bellman–Ford is widely used in areas such as network routing, currency exchange analysis, financial modeling, and graph optimization problems.</p><p>The algorithm was independently developed by <a href="https://en.wikipedia.org/wiki/Richard_Bellman">Richard Bellman</a> and <a href="https://en.wikipedia.org/wiki/L._R._Ford_Jr.">Lester Ford Jr</a>. in the 1950s and remains a foundational concept in graph theory and algorithm design. Its ability to handle negative weights and detect negative cycles makes it especially useful in situations where path costs are not strictly positive.</p><p>At its core, Bellman–Ford repeatedly relaxes every edge in the graph. Each relaxation step attempts to improve the shortest known distance to a node. By repeatedly applying these updates, the algorithm gradually propagates shortest-path information throughout the graph until the optimal solution is reached.</p><p>In this article, we’ll break down how Bellman–Ford works, implement it step by step in Java, explore negative cycle detection, and examine practical examples that demonstrate where and why it is useful.</p><h3>What Is Bellman–Ford? 🔍</h3><p>Bellman–Ford finds the shortest path from a starting node to every other reachable node in a weighted graph, even when some edges have negative weights.</p><p>A weighted graph is a graph where each connection (edge) has an associated value, such as distance, cost, profit, travel time, or latency. The goal is to find paths that minimize the total accumulated weight.</p><p>The algorithm works by repeatedly relaxing every edge in the graph:</p><ul><li>Choose a starting node (source)</li><li>Assign a distance of 0 to the source node</li><li>Assign ∞ (infinity) to all other nodes</li><li>Relax every edge in the graph</li><li>Repeat the relaxation process V − 1 times</li><li>Perform one additional pass to detect negative cycles</li></ul><p>Where:</p><ul><li>V = number of vertices in the graph</li></ul><p>A relaxation step checks whether traveling through one node produces a shorter path to another node. If a better path is discovered, the distance is updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DhVYITNLxxFJamVPxRWqQg.gif" /><figcaption>Animation of Bellman-Ford Algorithm. Michel Bakni, via Wikimedia Commons</figcaption></figure><p>A useful way to visualize Bellman–Ford is to imagine shortest-path information gradually spreading across the graph. Each iteration allows information to travel one edge farther from the source node. After V − 1 iterations, every shortest path has had enough opportunities to propagate through the graph.</p><p>Rather than prioritizing specific nodes, Bellman–Ford systematically examines every edge multiple times until no further improvements are possible. This repeated relaxation process is what allows the algorithm to correctly handle negative edge weights while still producing optimal shortest paths.</p><h3>When Should You Use Bellman–Ford? 🧐</h3><p>As mentioned earlier, the Bellman–Ford algorithm is specifically designed for graphs that may contain negative edge weights. In graph theory, an edge weight represents the cost of traveling from one node (vertex) to another. Depending on the application, this cost can represent:</p><ul><li>Distance</li><li>Profit or loss</li><li>Currency exchange gains</li><li>Energy consumption</li><li>Resource allocation</li><li>Network cost</li></ul><p>Rather than minimizing the number of steps, Bellman–Ford minimizes the total accumulated cost required to reach a destination. Because it supports negative edge weights, Bellman–Ford is useful in many optimization problems where certain actions can reduce the overall cost. Common applications include:</p><ul><li>Network routing protocols</li><li>Currency exchange and arbitrage detection</li><li>Financial modeling</li><li>Resource planning systems</li><li>Transportation networks with incentives or discounts</li></ul><p>Another important feature of Bellman–Ford is its ability to detect negative-weight cycles. A negative-weight cycle is a cycle whose total weight is less than zero. Since repeatedly traversing such a cycle continuously reduces the path cost, a shortest path may not exist.</p><p>The algorithm runs with a time complexity of O(VE), where:</p><ul><li>V = number of vertices</li><li>E = number of edges</li></ul><p>Its space complexity is O(V) since it only stores shortest-path distances and optional parent references for path reconstruction.</p><h3>Limitations of Bellman–Ford 📉</h3><p>Although Bellman–Ford is a powerful shortest-path algorithm, it also has several important limitations.</p><p><strong>Computationally Expensive: </strong>Bellman–Ford repeatedly processes every edge in the graph over multiple iterations. This results in a time complexity of O(VE), which can become costly as the number of vertices and edges increases.</p><p><strong>Negative Cycles Prevent Valid Solutions: </strong>If a graph contains a reachable negative-weight cycle, no finite shortest path exists. Since traversing the cycle repeatedly continues to reduce the total path cost, the concept of a “shortest” path becomes undefined. While Bellman–Ford can detect these cycles, it cannot produce a valid shortest-path solution when they are present.</p><p><strong>Less Suitable for Large Graphs: </strong>Because every edge may be examined many times, the algorithm can become expensive on large graphs. As graph size grows, execution time increases significantly, making Bellman–Ford less practical for performance-critical applications.</p><p><strong>Unnecessary Work in Some Cases: </strong>The standard Bellman–Ford algorithm performs exactly V − 1 relaxation rounds, even if the shortest paths have already been found earlier. This can lead to unnecessary computation on graphs where distances stabilize quickly.</p><p>Many implementations address this by terminating early when an iteration completes without any distance updates.</p><p>Despite these limitations, Bellman–Ford remains a fundamental algorithm in graph theory. Its simplicity, reliability, and ability to detect negative-weight cycles make it an important tool for shortest-path and graph optimization problems.</p><h3>From Theory to Practice 🛠️</h3><p>Now that we understand the theory behind Bellman–Ford, let’s see how the algorithm can be implemented in Java.</p><p>The implementation is surprisingly straightforward. We maintain an array containing the shortest known distance to every vertex and repeatedly relax all edges in the graph. After completing the relaxation phase, we perform one final pass to determine whether a negative-weight cycle exists.</p><p>Although graph representations can vary, Bellman–Ford is commonly implemented using an edge list because the algorithm repeatedly processes every edge during each iteration.</p><h4>1. Bellman–Ford Graph Implementation</h4><p>To understand how Bellman–Ford works in practice, we’ll start with a simple edge-list implementation.</p><p>An edge list stores each graph connection as an edge containing:</p><ul><li>A source vertex</li><li>A destination vertex</li><li>A weight (cost)</li></ul><p>Since Bellman–Ford repeatedly processes every edge, an edge list provides a clean and efficient way to represent the graph. The implementation below computes the shortest distance from a source vertex to every other vertex in the graph.</p><pre>import java.util.*;<br><br>class Edge {<br>    int from;<br>    int to;<br>    int weight;<br><br>    public Edge(int from, int to, int weight) {<br>        this.from = from;<br>        this.to = to;<br>        this.weight = weight;<br>    }<br>}<br><br>public class Main {<br><br>    public static void bellmanFord(List&lt;Edge&gt; edges, int vertices, int source) {<br><br>        // Store the shortest known distance to every vertex<br>        int[] dist = new int[vertices];<br><br>        // Initialize all distances to infinity<br>        Arrays.fill(dist, Integer.MAX_VALUE);<br><br>        // Distance from source to itself is zero<br>        dist[source] = 0;<br><br>        // Perform V - 1 relaxation passes<br>        for (int i = 1; i &lt; vertices; i++) {<br><br>            // Examine every edge in the graph<br>            for (Edge edge : edges) {<br><br>                // Skip unreachable vertices and relax the edge<br>                // if a shorter path exists<br>                if (dist[edge.from] != Integer.MAX_VALUE<br>                        &amp;&amp; dist[edge.from] + edge.weight &lt; dist[edge.to]) {<br><br>                    dist[edge.to] = dist[edge.from] + edge.weight;<br>                }<br>            }<br>        }<br><br>        // Print the final shortest distances<br>        System.out.println(&quot;Shortest distances from node &quot; + source);<br><br>        for (int i = 0; i &lt; vertices; i++) {<br>            System.out.println(&quot;To &quot; + i + &quot; = &quot; + dist[i]);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        List&lt;Edge&gt; edges = new ArrayList&lt;&gt;();<br><br>        // Build the graph<br>        edges.add(new Edge(0, 1, 4));<br>        edges.add(new Edge(0, 2, 5));<br>        edges.add(new Edge(1, 2, -2));<br>        edges.add(new Edge(2, 3, 3));<br><br>        // Compute shortest paths<br>        bellmanFord(edges, 4, 0);<br>    }<br>}<br><br>// Output:<br>// Shortest distances from node 0<br>// To 0 = 0<br>// To 1 = 4<br>// To 2 = 2<br>// To 3 = 5</pre><p>This implementation demonstrates the three core operations of the Bellman–Ford algorithm:</p><ul><li>Distance initialization</li><li>Repeated edge relaxation</li><li>Shortest-path computation</li></ul><p>Notice that the graph contains a negative-weight edge from vertex 1 to vertex 2. During the relaxation process, Bellman–Ford automatically incorporates this lower-cost connection whenever it produces a shorter path. Over successive iterations, these improvements propagate throughout the graph until the shortest distances are discovered.</p><p>Although this example contains only a few vertices, the same process scales to much larger graphs. Regardless of graph size, Bellman–Ford repeatedly relaxes edges until every reachable shortest path has been identified.</p><p>In the next section, we’ll examine the relaxation operation in detail and see why it is the fundamental building block of the Bellman–Ford algorithm.</p><h4>2. Understanding Edge Relaxation</h4><p>The heart of the Bellman–Ford algorithm is a process called edge relaxation.</p><p>Relaxation is the operation that allows the algorithm to gradually discover shorter paths throughout the graph. Every time Bellman–Ford examines an edge, it checks whether that edge provides a better route to its destination than the best route found so far.</p><p>In other words, the algorithm repeatedly asks: <em>“Can I reach this vertex more cheaply through this edge?”. </em>If the answer is yes, the distance is updated. Let’s look at a simple example. Suppose the current shortest distance to vertex <strong>A</strong> is:</p><pre>distance[A] = 5</pre><p>And we have the following edge:</p><pre>A → B (weight = 3)</pre><p>If we travel from the source to <strong>A</strong> and then follow the edge to <strong>B</strong>, the total cost becomes:</p><pre>5 + 3 = 8</pre><p>Now assume the current distance to <strong>B</strong> is 10. Since <strong>8</strong> is smaller than <strong>10</strong>, we have discovered a better path and should update the distance:</p><pre>if (distance[source] + weight &lt;<br>    distance[destination]) {<br><br>    distance[destination] =<br>            distance[source] + weight;<br>}</pre><p>This update is known as relaxing the edge. Bellman–Ford performs this operation on every edge in the graph during each iteration. As new and shorter paths are discovered, those improvements propagate to other vertices during subsequent relaxation passes.</p><p>Over time, the distance estimates become increasingly accurate. After <strong>V − 1</strong> iterations, all shortest paths have been discovered, assuming the graph does not contain a reachable negative-weight cycle.</p><h4>3. Negative Cycle Detection</h4><p>One of Bellman–Ford’s most useful features is its ability to detect negative-weight cycles.</p><p>A negative-weight cycle is a cycle whose total weight is less than zero. Each time the cycle is traversed, the total path cost decreases. For example, consider the following cycle:</p><pre>A → B (2)<br>B → C (-5)<br>C → A (1)</pre><p>The total weight of the cycle is:</p><pre>2 + (-5) + 1 = -2</pre><p>Every trip around the cycle reduces the total cost by 2. Since the cycle can be traversed repeatedly, the path cost can continue decreasing indefinitely. Because of this, a graph containing a reachable negative-weight cycle has no valid shortest-path solution. Fortunately, Bellman–Ford can detect these situations.</p><p>After completing the standard V − 1 relaxation passes, the algorithm performs one additional pass through all edges.</p><pre>boolean hasNegativeCycle = false;<br><br>for (Edge edge : edges) {<br>    if (dist[edge.from] != Integer.MAX_VALUE &amp;&amp;<br>        dist[edge.from] + edge.weight &lt; dist[edge.to]) {<br>        hasNegativeCycle = true;<br>        break;<br>    }<br>}<br><br>System.out.println(<br>        &quot;Negative cycle detected: &quot; +<br>        hasNegativeCycle<br>);</pre><p>This works because after V − 1 iterations, every shortest path should already be finalized. If another relaxation still improves a distance, then some path can continue becoming cheaper indefinitely.</p><p>This situation is only possible when a negative-weight cycle exists. A graph containing a reachable negative cycle has no valid shortest-path solution because repeatedly traversing the cycle continuously reduces the total path cost.</p><h4>4. Bellman–Ford Shortest Path Reconstruction</h4><p>In many practical applications, knowing only the shortest distance is not enough. We often need the actual sequence of vertices that forms the shortest path.</p><p>To support path reconstruction, Bellman–Ford can be extended with a parent array. Whenever a relaxation discovers a better path, the algorithm records which vertex produced the improvement.</p><pre>int[] parent = new int[vertices];<br><br>Arrays.fill(parent, -1);</pre><p>Whenever a shorter path is found:</p><pre>dist[edge.to] = dist[edge.from] + edge.weight;<br>parent[edge.to] = edge.from;</pre><p>The parent array stores the previous vertex used to reach each destination along the current shortest path. After the algorithm finishes, the route can be reconstructed by following these parent references backward.</p><pre>import java.util.*;<br><br>class Edge {<br>    int from;<br>    int to;<br>    int weight;<br><br>    public Edge(int from, int to, int weight) {<br>        this.from = from;<br>        this.to = to;<br>        this.weight = weight;<br>    }<br>}<br><br>public class Main {<br><br>    public static void bellmanFord(List&lt;Edge&gt; edges, int vertices, int source) {<br><br>        // Shortest distances from the source<br>        int[] dist = new int[vertices];<br><br>        // Parent array for path reconstruction<br>        int[] parent = new int[vertices];<br><br>        Arrays.fill(dist, Integer.MAX_VALUE);<br>        Arrays.fill(parent, -1);<br><br>        dist[source] = 0;<br><br>        // Perform V - 1 relaxation passes<br>        for (int i = 1; i &lt; vertices; i++) {<br><br>            for (Edge edge : edges) {<br><br>                if (dist[edge.from] != Integer.MAX_VALUE<br>                        &amp;&amp; dist[edge.from] + edge.weight &lt; dist[edge.to]) {<br><br>                    // Update shortest distance<br>                    dist[edge.to] = dist[edge.from] + edge.weight;<br><br>                    // Record predecessor<br>                    parent[edge.to] = edge.from;<br>                }<br>            }<br>        }<br><br>        // Print results<br>        System.out.println(&quot;Shortest paths from vertex &quot; + source + &quot;:&quot;);<br><br>        for (int v = 0; v &lt; vertices; v++) {<br><br>            System.out.print(&quot;To &quot; + v + &quot;: &quot;);<br><br>            if (dist[v] == Integer.MAX_VALUE) {<br>                System.out.println(&quot;No path&quot;);<br>                continue;<br>            }<br><br>            System.out.print(&quot;Distance = &quot; + dist[v] + &quot;, Path = &quot;);<br>            printPath(parent, v);<br>            System.out.println();<br>        }<br>    }<br><br>    // Recursively prints the path from source to vertex<br>    public static void printPath(int[] parent, int vertex) {<br><br>        if (vertex == -1) {<br>            return;<br>        }<br><br>        printPath(parent, parent[vertex]);<br>        System.out.print(vertex + &quot; &quot;);<br>    }<br><br>    public static void main(String[] args) {<br><br>        List&lt;Edge&gt; edges = new ArrayList&lt;&gt;();<br><br>        // Build the graph<br>        edges.add(new Edge(0, 1, 4));<br>        edges.add(new Edge(0, 2, 5));<br>        edges.add(new Edge(1, 2, -2));<br>        edges.add(new Edge(2, 3, 3));<br>        edges.add(new Edge(3, 4, 2));<br>        edges.add(new Edge(2, 4, 10));<br><br>        // Compute shortest paths from vertex 0<br>        bellmanFord(edges, 5, 0);<br>    }<br>}<br><br>// Output:<br>// Shortest paths from vertex 0:<br>// To 0: Distance = 0, Path = 0 <br>// To 1: Distance = 4, Path = 0 1 <br>// To 2: Distance = 2, Path = 0 1 2 <br>// To 3: Distance = 5, Path = 0 1 2 3 <br>// To 4: Distance = 7, Path = 0 1 2 3 4 </pre><p>This sequence represents the shortest path from the source vertex to vertex 4.</p><h4>5. Object-Oriented Bellman–Ford Implementation</h4><p>In larger applications, graphs are often represented using dedicated classes rather than standalone collections. This makes the code easier to organize, maintain, and extend.</p><p>The following implementation demonstrates Bellman–Ford using a simple Graph class and an edge-list representation.</p><pre>import java.util.*;<br><br>class Edge {<br><br>    int source;<br>    int destination;<br>    int weight;<br><br>    public Edge(<br>            int source,<br>            int destination,<br>            int weight) {<br><br>        this.source = source;<br>        this.destination = destination;<br>        this.weight = weight;<br>    }<br>}<br><br>class Graph {<br><br>    int vertices;<br><br>    // Store all graph edges<br>    List&lt;Edge&gt; edges = new ArrayList&lt;&gt;();<br><br>    public Graph(int vertices) {<br>        this.vertices = vertices;<br>    }<br><br>    // Add a directed edge to the graph<br>    public void addEdge(<br>            int source,<br>            int destination,<br>            int weight) {<br><br>        edges.add(<br>                new Edge(<br>                        source,<br>                        destination,<br>                        weight<br>                )<br>        );<br>    }<br><br>    public void bellmanFord(int source) {<br><br>        // Store shortest known distances<br>        int[] distance = new int[vertices];<br><br>        // Initialize all distances to infinity<br>        Arrays.fill(<br>                distance,<br>                Integer.MAX_VALUE<br>        );<br><br>        // Distance from source to itself is zero<br>        distance[source] = 0;<br><br>        // Perform V - 1 relaxation passes<br>        for (int i = 1; i &lt; vertices; i++) {<br><br>            // Examine every edge<br>            for (Edge edge : edges) {<br><br>                // Relax the edge if a shorter path is found<br>                if (distance[edge.source]<br>                        != Integer.MAX_VALUE &amp;&amp;<br>                    distance[edge.source]<br>                            + edge.weight &lt;<br>                    distance[edge.destination]) {<br><br>                    distance[edge.destination] =<br>                            distance[edge.source]<br>                                    + edge.weight;<br>                }<br>            }<br>        }<br><br>        // Perform one additional pass to detect<br>        // negative-weight cycles<br>        for (Edge edge : edges) {<br><br>            if (distance[edge.source]<br>                    != Integer.MAX_VALUE &amp;&amp;<br>                distance[edge.source]<br>                        + edge.weight &lt;<br>                distance[edge.destination]) {<br><br>                System.out.println(<br>                        &quot;Negative cycle detected!&quot;<br>                );<br><br>                return;<br>            }<br>        }<br><br>        // Print the final shortest distances<br>        System.out.println(<br>                Arrays.toString(distance)<br>        );<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        Graph graph = new Graph(5);<br>        <br>        graph.addEdge(0, 1, 6);<br>        graph.addEdge(0, 2, 7);<br>        graph.addEdge(1, 2, 8);<br>        graph.addEdge(1, 3, 5);<br>        graph.addEdge(1, 4, -4);<br>        graph.addEdge(2, 3, -3);<br>        graph.addEdge(2, 4, 9);<br>        graph.addEdge(3, 1, -2);<br>        graph.addEdge(4, 0, 2);<br>        graph.addEdge(4, 3, 7);<br>        graph.bellmanFord(0);<br>    }<br>}<br><br>// Output:<br>// [0, 2, 7, 4, -2]</pre><p>Now we can build a graph and execute the algorithm. Notice that several edges have negative weights. This is exactly the type of graph Bellman–Ford was designed to handle. Through repeated relaxation, the algorithm correctly propagates shorter paths throughout the graph while also verifying that no negative-weight cycles are present.</p><h3>Practical Examples 💡</h3><p>Bellman–Ford is more than a theoretical shortest-path algorithm. It is used to solve optimization problems where costs, rewards, discounts, or incentives influence the best route through a network.</p><p>Many shortest-path algorithms assume that every transition has a non-negative cost. Bellman–Ford is different. It can correctly handle situations where certain actions reduce the overall cost and can even detect cycles that continuously decrease cost.</p><p>Let’s explore a few practical examples.</p><h4>1. Network Routing</h4><p>One of the most well-known applications of Bellman–Ford is network routing.</p><p>Modern computer networks consist of routers connected by communication links. Whenever data needs to travel from one machine to another, routers must determine the most efficient path through the network. In graph terminology, routers are represented as vertices, network connections are represented as edges, and each edge is assigned a weight that reflects the cost of using that connection.</p><p>In a networking context, cost does not necessarily refer to physical distance. Instead, it represents a routing metric that indicates how desirable a connection is. Depending on the network, this metric may reflect latency, hop count, bandwidth consumption, congestion, or a combination of several factors.</p><p>For example, consider the following connections:</p><pre>Router 0 --(4)--&gt; Router 1<br>Router 0 --(3)--&gt; Router 2</pre><p>The weights indicate the relative cost of using each route. A weight of 3 might represent a faster or less congested connection, while a weight of 4 could represent a slower or more heavily utilized link. Because Bellman–Ford minimizes the total accumulated cost, it automatically favors routes whose combined weights are lower, even when those routes pass through additional routers.</p><p>The objective is therefore to determine the lowest-cost path from a source router to every other router in the network.</p><pre>public static void main(String[] args) {<br><br>    Graph network = new Graph(7);<br><br>    // Router 0 -&gt; Router 1<br>    // Cost = 4 (slightly slower or more congested connection)<br>    network.addEdge(0, 1, 4);<br><br>    // Router 0 -&gt; Router 2<br>    // Cost = 3 (faster or more efficient connection)<br>    network.addEdge(0, 2, 3);<br><br>    // Router 1 -&gt; Router 3<br>    // Cost = 2<br>    network.addEdge(1, 3, 2);<br><br>    // Router 1 -&gt; Router 4<br>    // Cost = 7 (expensive route)<br>    network.addEdge(1, 4, 7);<br><br>    // Router 2 -&gt; Router 1<br>    // Cost = 6<br>    network.addEdge(2, 1, 6);<br><br>    // Router 2 -&gt; Router 4<br>    // Cost = 4<br>    network.addEdge(2, 4, 4);<br><br>    // Router 3 -&gt; Router 5<br>    // Cost = 1 (very efficient link)<br>    network.addEdge(3, 5, 1);<br><br>    // Router 4 -&gt; Router 5<br>    // Cost = 3<br>    network.addEdge(4, 5, 3);<br><br>    // Router 4 -&gt; Router 6<br>    // Cost = 5<br>    network.addEdge(4, 6, 5);<br><br>    // Router 5 -&gt; Router 6<br>    // Cost = 2<br>    network.addEdge(5, 6, 2);<br><br>    // Find the lowest-cost routes from Router 0<br>    network.bellmanFord(0);<br>}<br><br>// Output:<br>// [0, 4, 3, 6, 7, 7, 9]</pre><p>Bellman–Ford evaluates every available route and gradually refines its distance estimates until the lowest-cost paths are discovered. For example, the path:</p><pre>0 → 2 → 4 = 7</pre><p>has a lower total cost than:</p><pre>0 → 1 → 4 = 11</pre><p>Even though both routes reach the same destination, Bellman–Ford correctly identifies the cheaper option by comparing the accumulated cost of each path.</p><p>Although routing metrics are typically positive, this example demonstrates the fundamental shortest-path problem that Bellman–Ford was designed to solve: finding the minimum-cost route through a network of interconnected nodes.</p><h4>2. Supply Chain Optimization</h4><p>Supply-chain systems often involve more than simple transportation costs. Companies may receive bulk-purchase discounts, shipping rebates, tax incentives, or supplier credits that reduce the overall cost of moving goods through a network. These incentives can be modeled naturally using negative edge weights.</p><p>Imagine a company shipping products from a factory to a customer.</p><pre>public static void main(String[] args) {<br><br>    Graph supplyChain = new Graph(6);<br><br>    // Factory -&gt; Warehouse<br>    // Transportation cost = $12<br>    supplyChain.addEdge(0, 1, 12);<br><br>    // Warehouse -&gt; Distribution Center<br>    // Standard shipping cost = $8<br>    supplyChain.addEdge(1, 2, 8);<br><br>    // Warehouse -&gt; Discount Program<br>    // Cost = -5 because a bulk-order rebate saves $5<br>    supplyChain.addEdge(1, 3, -5);<br><br>    // Discount Program -&gt; Distribution Center<br>    // Additional processing cost = $2<br>    supplyChain.addEdge(3, 2, 2);<br><br>    // Distribution Center -&gt; Retail Store<br>    // Delivery cost = $7<br>    supplyChain.addEdge(2, 4, 7);<br><br>    // Retail Store -&gt; Customer<br>    // Final delivery cost = $3<br>    supplyChain.addEdge(4, 5, 3);<br><br>    // Find the lowest overall shipping cost<br>    supplyChain.bellmanFord(0);<br>}<br><br>// Output:<br>// [0, 12, 9, 7, 16, 19]</pre><p>The interesting edge is:</p><pre>supplyChain.addEdge(1, 3, -5);</pre><p>This edge represents a bulk-order discount. Normally, moving goods from the warehouse to the distribution center would incur an additional cost of 8. However, by taking advantage of the discount, Bellman–Ford discovers an alternative route whose combined cost is -5 + 2 = -3.</p><p>This example illustrates one of Bellman–Ford’s key advantages. Instead of assuming that every transition increases cost, the algorithm can incorporate both expenses and cost-saving incentives when determining the optimal path.</p><p>As a result, Bellman–Ford is well suited for logistics, manufacturing, resource allocation, and other optimization problems where discounts, rebates, or credits influence decision-making. Unlike Dijkstra’s algorithm, it can correctly handle these negative-weight relationships.</p><h4>3. Currency Arbitrage Detection</h4><p>One of the most famous applications of Bellman–Ford is arbitrage detection in financial markets.</p><p>An arbitrage opportunity occurs when a trader can move money through a sequence of currency exchanges and end up with more money than they started with. Because currencies and exchange opportunities form a network, they can be modeled naturally as a graph. In this representation, vertices represent currencies, edges represent exchange opportunities, and edge weights represent the effective cost or gain associated with each exchange.</p><p>In real financial systems, exchange rates are typically transformed mathematically so that profitable trading loops appear as negative-weight cycles. Once this transformation is applied, Bellman–Ford can automatically detect potential arbitrage opportunities.</p><pre>public static void main(String[] args) {<br><br>    Graph exchange = new Graph(4);<br><br>    // USD -&gt; EUR<br>    // Effective trading cost = 2<br>    exchange.addEdge(0, 1, 2);<br><br>    // EUR -&gt; GBP<br>    // Effective gain represented as a negative cost<br>    exchange.addEdge(1, 2, -5);<br><br>    // GBP -&gt; USD<br>    // Conversion cost = 1<br>    exchange.addEdge(2, 0, 1);<br><br>    // USD -&gt; JPY<br>    // Conversion cost = 4<br>    exchange.addEdge(0, 3, 4);<br><br>    // JPY -&gt; GBP<br>    // Conversion cost = 2<br>    exchange.addEdge(3, 2, 2);<br><br>    // Detect arbitrage opportunities<br>    exchange.bellmanFord(0);<br>}<br><br>// Output:<br>// Negative cycle detected!</pre><p>Consider the cycle:</p><pre>USD → EUR → GBP → USD</pre><p>The total weight of this cycle is:</p><pre>2 + (-5) + 1 = -2</pre><p>Because the cycle has a negative total weight, each trip around the loop reduces the overall cost. Unlike an ordinary shortest-path problem, there is no stable minimum cost because the cycle can be traversed repeatedly, making the path cost smaller and smaller. Bellman–Ford detects this condition during its final verification pass and reports:</p><pre>Negative cycle detected!</pre><p>This capability is one of the algorithm’s most important features. In financial systems, a negative-weight cycle may indicate a potential arbitrage opportunity. More generally, negative cycles often reveal situations where costs can be reduced indefinitely, meaning that a valid shortest path may not exist.</p><h3>Conclusion 📣</h3><p>Bellman–Ford is one of the most versatile shortest-path algorithms in graph theory. Unlike many alternatives, it can correctly handle graphs that contain negative edge weights while also detecting negative-weight cycles that make a valid shortest path impossible.</p><p>In this article, we explored how Bellman–Ford works through repeated edge relaxation, learned how shortest-path information propagates through a graph over multiple iterations, and examined how the algorithm detects negative cycles using a final verification pass. We also extended the basic implementation with path reconstruction, allowing us to recover not only the minimum cost but also the exact route used to reach a destination.</p><p>Although Bellman–Ford has a higher time complexity of O(VE) than algorithms such as Dijkstra’s algorithm, its support for negative weights makes it an essential tool for solving many real-world optimization problems. Applications such as network routing, supply-chain optimization, financial modeling, and currency arbitrage detection often involve costs, discounts, incentives, or gains that cannot be represented using strictly positive weights.</p><p>While it may not be the fastest shortest-path algorithm, Bellman–Ford remains one of the most important. Its simplicity, reliability, and ability to reason about both positive and negative costs make it a foundational algorithm that every Java developer and computer science student should understand. Whether you’re optimizing network traffic, modeling transportation systems, or analyzing financial opportunities, Bellman–Ford provides a powerful and practical approach to finding optimal paths in weighted graphs.</p><p>Thanks for reading! Please give this article a clap and follow me if you enjoyed it 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9442f7392cec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A* Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://levelup.gitconnected.com/a-algorithm-in-java-learn-with-practical-examples-bb070a8909a8?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb070a8909a8</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[astar]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 09:21:01 GMT</pubDate>
            <atom:updated>2026-06-14T23:45:36.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGSjX5yqZ79b7gIPeY8t7g.png" /></figure><p>A* (pronounced “A-star”) is one of the most influential and widely used pathfinding algorithms in computer science. Whenever a system needs to find the shortest route between two points — whether in a video game, a GPS navigation system, or a robot’s environment — it faces a fundamental challenge: how to find the best path without wasting time exploring countless unnecessary alternatives.</p><p>Developed in 1968 by <a href="https://en.wikipedia.org/wiki/Peter_E._Hart">Peter Hart</a>, <a href="https://en.wikipedia.org/wiki/Nils_John_Nilsson">Nils Nilsson</a>, and <a href="https://en.wikipedia.org/wiki/Bertram_Raphael">Bertram Raphael</a>, A* solves this problem by combining two key pieces of information: the cost of the path traveled so far and a heuristic estimate of the remaining distance to the goal. By balancing these factors, the algorithm focuses its search on the most promising routes instead of examining every possible option. The result is a method that is both efficient and reliable, capable of finding optimal paths while significantly reducing the amount of work required.</p><p>This balance between accuracy and performance has made A* a cornerstone of pathfinding and graph traversal for more than five decades. It is used extensively in game AI, robotics, GPS navigation, autonomous systems, puzzle solving, and many other applications where intelligent route planning is essential. Its elegant combination of graph search and heuristics has also secured its place as one of the most widely taught algorithms in computer science.</p><p>In this article, we’ll break down how A* works, implement it step by step in Java, and explore practical examples that demonstrate why it remains one of the most important pathfinding algorithms ever created.</p><h3>What Is the A* Algorithm? 🔍</h3><p>A* is a shortest-path search algorithm that finds the optimal route between a starting node and a target node by combining:<strong> the actual known path cost</strong>, and <strong>an estimated remaining distance to the goal</strong>. The algorithm continuously selects the path that currently appears most promising according to its estimated total cost. Here is the core idea:</p><ol><li>Choose a starting node</li><li>Assign a cost of 0 to the start node</li><li>Estimate the remaining distance to the target using a heuristic</li><li>Select the node with the smallest estimated total cost</li><li>Explore neighboring nodes</li><li>Update path costs if a shorter route is discovered</li><li>Repeat until the target node is reached</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*RFALeWgwNm5z44i2P7F0gw.gif" /><figcaption>Animation of A* algorithm. <a href="https://commons.wikimedia.org/wiki/File:AstarExampleEn.gif">CountingPine</a>, CC0, via Wikimedia Commons</figcaption></figure><p>A useful way to visualize A* is to imagine a traveler navigating toward a destination while constantly asking: <em>“Which path currently looks cheapest overall?”</em></p><h3>Understanding the Heuristic Function 🧠</h3><p>The heuristic function is the core component that gives A* its intelligence and efficiency. It estimates the remaining cost from the current node to the target node, allowing the algorithm to identify and prioritize the most promising paths to explore next. A* makes decisions using two important values:</p><ul><li><strong>g(n)</strong> is the actual cost required to reach a node</li><li><strong>h(n)</strong> is a heuristic estimate of the remaining distance to the goal</li></ul><p>These values are combined into a single score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*u_u8fjXUFH6Dhg1pyyFcxQ.png" /></figure><p>The node with the lowest <strong>f(n)</strong> value is explored first. This balance between the known path cost and the estimated remaining distance is what makes A* both efficient and effective.</p><p>The quality of the heuristic has a major impact on performance. A weak heuristic causes A* to explore many unnecessary nodes, behaving similarly to Dijkstra’s algorithm. A stronger heuristic focuses the search more directly toward the goal, often reducing the number of explored nodes dramatically. Common heuristic functions include:</p><ul><li>Manhattan distance</li><li>Euclidean distance</li><li>Chebyshev distance</li><li>Straight-line distance</li></ul><p>As example, the <strong>Manhattan distance heuristic</strong> measures the number of horizontal and vertical steps required to reach the target. It is commonly used in grid-based environments where movement is restricted to four directions: up, down, left, and right. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*vezq99Cq2vFcMFuUUAjw0g.png" /></figure><p>For instance, moving from (1,1) to (4,5) gives |1 - 4| + |1 - 5| = 7, which results in a total Manhattan distance of 7.</p><p>A useful way to visualize Manhattan distance is to imagine navigating city blocks in Manhattan, where movement is limited to streets and intersections rather than diagonal shortcuts through buildings.</p><h4>Heuristic Admissibility</h4><p>An important concept in A* is heuristic admissibility. A heuristic is considered <strong>admissible</strong> if it never overestimates the true remaining cost to the goal. When an admissible heuristic is used, A* guarantees the shortest possible path.</p><p>A <strong>non-admissible</strong> heuristic may produce faster searches because it prioritizes aggressive estimates, but it can sacrifice optimality by missing the true shortest path. This creates a trade-off between accuracy and performance.</p><p>In practice, the ideal heuristic strikes a balance: it guides the search efficiently while remaining admissible, allowing A* to reach the destination with minimal unnecessary exploration while still guaranteeing an optimal solution.</p><h4>Choosing the Correct Heuristics</h4><p>The heuristic function is what gives A* its intelligence. It is essentially an informed guess about the remaining distance to the goal. It doesn’t need to be exact — but the closer it is to reality, the more efficiently A* performs. The choice of heuristic has a direct impact on:</p><ul><li>how many nodes are explored</li><li>how fast the search completes</li><li>whether the path remains optimal</li><li>overall algorithm efficiency</li></ul><p>Different movement systems require different heuristics, depending on how entities are allowed to move. Let’s explore the most common heuristics.</p><p><strong>Manhattan Distance Heuristic </strong>measures how far two points are when movement is restricted to horizontal and vertical steps only. It is commonly used in grid-based games, tile maps, maze solvers, and pathfinding systems with 4-direction movement. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*vezq99Cq2vFcMFuUUAjw0g.png" /></figure><p>This heuristic works well when diagonal movement is not allowed.</p><pre>public static int manhattan(int x1, int y1, int x2, int y2) {<br>    return Math.abs(x1 - x2) + Math.abs(y1 - y2);<br>}<br><br>// As example from (1, 1) to (4,5):<br>// = |1 - 4| + |1 - 5|<br>// = 3 + 4<br>// = 7</pre><p><strong>Euclidean Distance Heuristic</strong> measures the straight-line geometric distance between two points. It is used when movement is not restricted to grid directions, such as continuous movement systems, robotics, physics simulations, and open-world navigation. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*a4CY1WpokeDC5fetAZdYUw.png" /></figure><pre>public static double euclidean(int x1, int y1, int x2, int y2) {<br>    int dx = x2 - x1;<br>    int dy = y2 - y1;<br>    return Math.sqrt(dx * dx + dy * dy);<br>}<br><br>// As example, from (1,1) to (4,5):<br>// = √((4 - 1)^2 + (5 - 1)^2)<br>// = √(9 + 16)<br>// = √25<br>// = 5</pre><p><strong>Chebyshev Distance Heuristic</strong> applies when movement is allowed in all eight directions and diagonal movement has the same cost as straight movement. It is commonly used in chess-like movement systems, 8-direction grid navigation, and strategy games. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*Hjk9J0lmogAtYkCeb8GGwA.png" /></figure><p>Instead of summing distances, Chebyshev distance takes the larger coordinate difference.</p><pre>public static int chebyshev(int x1, int y1, int x2, int y2) {<br>    return Math.max(<br>        Math.abs(x1 - x2),<br>        Math.abs(y1 - y2)<br>    );<br>}<br><br>// As example, from (1,1) to (4,5):<br>// = max(|1 - 4|, |1 - 5|)<br>// = max(3, 4)<br>// = 4</pre><p><strong>Straight-Line Distance Heuristic</strong> is conceptually the same as Euclidean distance but is often used in geographic or navigation systems where the idea of “as-the-crow-flies” distance is more intuitive. Typical use cases are GPS navigation, airline routing, and geographical systems. The formula is identical to Euclidean distance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*a4CY1WpokeDC5fetAZdYUw.png" /></figure><p>The difference is primarily conceptual rather than mathematical.</p><pre>public static double straightLineDistance(<br>        double lat1,<br>        double lon1,<br>        double lat2,<br>        double lon2) {<br><br>    double dx = lat2 - lat1;<br>    double dy = lon2 - lon1;<br>    return Math.sqrt(dx * dx + dy * dy);<br>}<br><br>// As example, from (1,1) to (4,5):<br>// = sqrt((4 - 1)^2 + (5 - 1)^2)<br>// = sqrt(3^2 + 4^2)<br>// = sqrt(9 + 16)<br>// = sqrt(25)<br>// = 5.0</pre><h3>Limitations of A* 📉</h3><p>Although A* is one of the most efficient and widely used pathfinding algorithms, it still has several limitations, especially in large or complex search spaces.</p><p><strong>Performance Depends on the Heuristic:</strong> The effectiveness of A* is heavily influenced by the quality of its heuristic function. A strong heuristic guides the search efficiently toward the goal, while a weak heuristic may cause the algorithm to explore many unnecessary nodes, reducing performance.</p><p><strong>High Memory Usage:</strong> A* stores explored nodes, distance information, and priority queue states throughout the search process. On very large maps or dense graphs, memory consumption can become a significant limitation.</p><p><strong>Optimality Is Not Always Guaranteed:</strong> A* guarantees the shortest path only when the heuristic is admissible, meaning it never overestimates the true remaining cost. Overestimating heuristics may improve speed but can produce suboptimal paths.</p><p><strong>Performance Can Decrease on Large Graphs:</strong> In very large or complicated environments, A* may still need to explore a large number of nodes, increasing computation time. Optimizations such as hierarchical pathfinding or Jump Point Search are often used to improve scalability.</p><p><strong>Designing a Good Heuristic Can Be Difficult:</strong> Different problem domains often require different heuristics. Choosing an ineffective heuristic can significantly reduce the efficiency of the algorithm.</p><p><strong>Not Ideal for Exhaustive Searches:</strong> A* is designed for goal-directed pathfinding. If the objective is to compute shortest paths to many nodes or analyze an entire graph, algorithms such as Dijkstra’s algorithm may be more suitable.</p><p>Despite these limitations, A* remains one of the most important pathfinding algorithms in computer science because it provides an excellent balance between efficiency, flexibility, and optimal pathfinding performance.</p><h3>From Theory to Practice 🛠️</h3><p>In this section, we will first examine how A* makes decisions internally and then apply these concepts to pathfinding examples using a variety of heuristics.</p><h4>1. Graph Implementation — Straight-Line (Euclidean) Distance</h4><p>A* can be applied to general weighted graphs, where nodes represent locations or states and edges represent connections with associated costs. This approach is commonly used in systems such as road networks, GPS navigation, and route planning, where each connection may represent a distance, travel time, or other movement cost.</p><p>Unlike grid-based pathfinding, graph structures are not limited to fixed movement directions. Instead, the algorithm explores neighboring nodes through an adjacency list, making it well suited for irregular and real-world networks.</p><p>In this implementation, the heuristic uses straight-line (Euclidean) distance to estimate how far a node is from the goal based on their coordinates. Since the nodes represent spatial positions, the direct geometric distance provides a natural approximation of the remaining path cost and helps guide the search more efficiently toward the destination.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Represents a graph node with x and y coordinates<br>    static class Point {<br>        int x, y;<br><br>        // Constructor to initialize coordinates<br>        Point(int x, int y) {<br>            this.x = x;<br>            this.y = y;<br>        }<br>    }<br><br>    // Represents a node used in the priority queue<br>    static class Node {<br>        String name;<br>        int g; // Actual cost from the start node<br>        double f; // Estimated total cost (g + h)<br><br>        // Constructor to initialize node values<br>        Node(String name, int g, double f) {<br>            this.name = name;<br>            this.g = g;<br>            this.f = f;<br>        }<br>    }<br><br>    // Represents a connection between two graph nodes<br>    static class Edge {<br>        String to; // Destination node<br>        int cost; // Cost to travel to destination<br><br>        // Constructor to initialize edge<br>        Edge(String to, int cost) {<br>            this.to = to;<br>            this.cost = cost;<br>        }<br>    }<br><br>    // Stores coordinates for each graph node<br>    static Map&lt;String, Point&gt; coordinates = new HashMap&lt;&gt;();<br><br>    // Heuristic function using Euclidean distance<br>    static double heuristic(String node, String goal) {<br><br>        // Get coordinates of current node and goal node<br>        Point a = coordinates.get(node);<br>        Point b = coordinates.get(goal);<br><br>        // Compute straight-line distance between nodes<br>        return Math.sqrt(<br>                Math.pow(a.x - b.x, 2) +<br>                Math.pow(a.y - b.y, 2)<br>        );<br>    }<br><br>    // A* search algorithm<br>    public static int aStar(<br>            Map&lt;String, List&lt;Edge&gt;&gt; graph,<br>            String start,<br>            String goal<br>    ) {<br><br>        // Stores shortest known distance from start to each node<br>        Map&lt;String, Integer&gt; dist = new HashMap&lt;&gt;();<br><br>        // Priority queue ordered by lowest estimated total cost<br>        PriorityQueue&lt;Node&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingDouble(n -&gt; n.f));<br><br>        // Initialize all node distances as infinity<br>        for (String node : graph.keySet()) {<br>            dist.put(node, Integer.MAX_VALUE);<br>        }<br><br>        // Distance to the start node is 0<br>        dist.put(start, 0);<br><br>        // Add start node to the priority queue<br>        pq.offer(<br>                new Node(<br>                        start,<br>                        0,<br>                        heuristic(start, goal) // Initial heuristic estimate<br>                )<br>        );<br><br>        // Continue searching while nodes remain<br>        while (!pq.isEmpty()) {<br><br>            // Get node with the smallest f value<br>            Node curr = pq.poll();<br><br>            // If goal is reached, return total cost<br>            if (curr.name.equals(goal)) {<br>                return curr.g;<br>            }<br><br>            // Explore all neighboring nodes<br>            for (Edge edge : graph.get(curr.name)) {<br><br>                // Compute new path cost to neighbor<br>                int newCost = curr.g + edge.cost;<br><br>                // If a shorter path is found<br>                if (newCost &lt; dist.get(edge.to)) {<br><br>                    // Update shortest known distance<br>                    dist.put(edge.to, newCost);<br><br>                    // Compute heuristic estimate to goal<br>                    double h = heuristic(edge.to, goal);<br><br>                    // Add updated node to priority queue<br>                    pq.offer(<br>                            new Node(<br>                                    edge.to,<br>                                    newCost,<br>                                    newCost + h // f = g + h<br>                            )<br>                    );<br>                }<br>            }<br>        }<br><br>        // Return -1 if goal cannot be reached<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Graph represented as an adjacency list<br>        Map&lt;String, List&lt;Edge&gt;&gt; graph = new HashMap&lt;&gt;();<br><br>        // Coordinates for each node<br>        coordinates.put(&quot;A&quot;, new Point(0, 0));<br>        coordinates.put(&quot;B&quot;, new Point(2, 1));<br>        coordinates.put(&quot;C&quot;, new Point(3, 3));<br>        coordinates.put(&quot;D&quot;, new Point(5, 4));<br><br>        // Add graph edges and costs<br>        graph.put(&quot;A&quot;, List.of(<br>                new Edge(&quot;B&quot;, 2),<br>                new Edge(&quot;C&quot;, 5)<br>        ));<br><br>        graph.put(&quot;B&quot;, List.of(<br>                new Edge(&quot;C&quot;, 1),<br>                new Edge(&quot;D&quot;, 4)<br>        ));<br><br>        graph.put(&quot;C&quot;, List.of(<br>                new Edge(&quot;D&quot;, 1)<br>        ));<br><br>        // Node D has no outgoing edges<br>        graph.put(&quot;D&quot;, List.of());<br><br>        // Run A* from node A to node D<br>        int result = aStar(graph, &quot;A&quot;, &quot;D&quot;);<br><br>        // Print the minimum path cost<br>        System.out.println(&quot;Minimum path cost: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum path cost: 4</pre><p>This graph-based version of A* searches through connected nodes in a weighted network while prioritizing paths that appear closer to the goal. The Euclidean distance heuristic is particularly effective in this scenario because it provides a realistic estimate of the remaining travel distance without overestimating the actual shortest path.</p><h4>2. Grid Implementation — Manhattan Distance (Cardinal Movement)</h4><p>A* is widely used for pathfinding on 2D grids, where each cell represents a node and movement occurs between neighboring cells. This type of structure is common in tile-based games, robotics, maze solving, and navigation systems.</p><p>In this implementation, movement is restricted to four directions: up, down, left, and right. Because diagonal movement is not allowed, the Manhattan distance heuristic is the most appropriate choice. It estimates the remaining distance by calculating the total horizontal and vertical movement required to reach the goal.</p><p>Each value in the grid represents the movement cost of entering a cell, while the heuristic helps guide the search toward the destination more efficiently.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    static class Node {<br>        int row, col;<br>        int g; // Cost from start to this node (actual path cost)<br>        int f; // Total estimated cost (g + h)<br><br>        Node(int row, int col, int g, int f) {<br>            this.row = row;<br>            this.col = col;<br>            this.g = g;<br>            this.f = f;<br>        }<br>    }<br><br>    // Heuristic function: Manhattan distance<br>    static int heuristic(int r, int c, int targetRow, int targetCol) {<br>        return Math.abs(r - targetRow) + Math.abs(c - targetCol);<br>    }<br><br>    public static int aStar(int[][] grid) {<br><br>        int rows = grid.length;<br>        int cols = grid[0].length;<br><br>        // Tracks the best known cost to reach each cell<br>        int[][] dist = new int[rows][cols];<br><br>        for (int[] row : dist) {<br>            Arrays.fill(row, Integer.MAX_VALUE);<br>        }<br><br>        // Possible movement directions (up, down, left, right)<br>        int[][] dirs = {<br>                {1, 0},<br>                {-1, 0},<br>                {0, 1},<br>                {0, -1}<br>        };<br><br>        // Priority queue orders nodes by lowest estimated total cost (f)<br>        PriorityQueue&lt;Node&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(n -&gt; n.f));<br><br>        // Initialize start node (0,0)<br>        dist[0][0] = grid[0][0];<br><br>        int startHeuristic =<br>                heuristic(0, 0, rows - 1, cols - 1);<br><br>        pq.offer(<br>                new Node(<br>                        0,<br>                        0,<br>                        grid[0][0],                 // g cost<br>                        grid[0][0] + startHeuristic // f = g + h<br>                )<br>        );<br><br>        while (!pq.isEmpty()) {<br><br>            // Node with lowest estimated total cost<br>            Node curr = pq.poll();<br><br>            int r = curr.row;<br>            int c = curr.col;<br><br>            // If we reached the goal, return the cost<br>            if (r == rows - 1 &amp;&amp; c == cols - 1) {<br>                return curr.g;<br>            }<br><br>            // Explore all 4 neighboring cells<br>            for (int[] d : dirs) {<br><br>                int nr = r + d[0];<br>                int nc = c + d[1];<br><br>                // Skip out-of-bounds neighbors<br>                if (nr &gt;= 0 &amp;&amp; nc &gt;= 0 &amp;&amp; nr &lt; rows &amp;&amp; nc &lt; cols) {<br><br>                    // Compute new cost to reach neighbor<br>                    int newCost = curr.g + grid[nr][nc];<br><br>                    // Only proceed if this path is better<br>                    if (newCost &lt; dist[nr][nc]) {<br><br>                        dist[nr][nc] = newCost;<br><br>                        int h = heuristic(nr, nc, rows - 1, cols - 1);<br><br>                        // Push neighbor with updated priority<br>                        pq.offer(<br>                                new Node(<br>                                        nr,<br>                                        nc,<br>                                        newCost,<br>                                        newCost + h<br>                                )<br>                        );<br>                    }<br>                }<br>            }<br>        }<br><br>        // If goal is unreachable<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[][] grid = {<br>                {1, 3, 1},<br>                {1, 5, 1},<br>                {4, 2, 1}<br>        };<br><br>        int result = aStar(grid);<br><br>        System.out.println(&quot;Minimum path cost: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum path cost: 7</pre><p>This grid-based version of A* combines the actual movement cost with a heuristic estimate to prioritize paths that are more likely to reach the goal quickly. Compared to Dijkstra’s algorithm, which explores nodes more uniformly, A* uses the Manhattan distance heuristic to focus the search in the direction of the target, significantly reducing the number of explored states in many pathfinding scenarios.</p><h4>3. Grid Implementation — Chebyshev Distance (Diagonal Movement)</h4><p>A* is commonly used on 2D grids that support both orthogonal and diagonal movement. This type of pathfinding is widely used in tile-based games, robotics, and navigation systems that allow movement in eight directions.</p><p>Unlike the previous grid example, which restricted movement to up, down, left, and right, this implementation also allows diagonal movement between cells. Because diagonal moves can reduce both the row and column distance at the same time, the Manhattan distance heuristic is no longer the most appropriate choice.</p><p>Instead, this implementation uses the Chebyshev distance heuristic. This heuristic works well for diagonal movement because a single diagonal step can reduce both the row and column distance simultaneously, providing a more accurate estimate of the remaining path cost in eight-direction movement systems.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Represents a grid node<br>    static class Node {<br>        int row, col;<br>        int g; // Actual cost from start<br>        int f; // Estimated total cost (g + h)<br><br>        // Constructor to initialize node values<br>        Node(int row, int col, int g, int f) {<br>            this.row = row;<br>            this.col = col;<br>            this.g = g;<br>            this.f = f;<br>        }<br>    }<br><br>    // Chebyshev distance heuristic<br>    static int heuristic(int r, int c, int targetRow, int targetCol) {<br><br>        return Math.max(<br>                Math.abs(r - targetRow),<br>                Math.abs(c - targetCol)<br>        );<br>    }<br><br>    public static int aStar(int[][] grid) {<br><br>        int rows = grid.length;<br>        int cols = grid[0].length;<br><br>        // Stores shortest known distance to each cell<br>        int[][] dist = new int[rows][cols];<br><br>        for (int[] row : dist) {<br>            Arrays.fill(row, Integer.MAX_VALUE);<br>        }<br><br>        // 8 possible movement directions<br>        int[][] dirs = {<br>                {1, 0},   // down<br>                {-1, 0},  // up<br>                {0, 1},   // right<br>                {0, -1},  // left<br>                {1, 1},   // down-right<br>                {1, -1},  // down-left<br>                {-1, 1},  // up-right<br>                {-1, -1}  // up-left<br>        };<br><br>        // Priority queue ordered by lowest f value<br>        PriorityQueue&lt;Node&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(n -&gt; n.f));<br><br>        // Initialize start position<br>        dist[0][0] = grid[0][0];<br><br>        int startHeuristic =<br>                heuristic(0, 0, rows - 1, cols - 1);<br><br>        pq.offer(<br>                new Node(<br>                        0,<br>                        0,<br>                        grid[0][0],<br>                        grid[0][0] + startHeuristic<br>                )<br>        );<br><br>        while (!pq.isEmpty()) {<br><br>            // Get node with smallest estimated cost<br>            Node curr = pq.poll();<br><br>            int r = curr.row;<br>            int c = curr.col;<br><br>            // Goal reached<br>            if (r == rows - 1 &amp;&amp; c == cols - 1) {<br>                return curr.g;<br>            }<br><br>            // Explore all 8 neighboring cells<br>            for (int[] d : dirs) {<br><br>                int nr = r + d[0];<br>                int nc = c + d[1];<br><br>                // Skip invalid positions<br>                if (nr &gt;= 0 &amp;&amp; nc &gt;= 0 &amp;&amp;<br>                    nr &lt; rows &amp;&amp; nc &lt; cols) {<br><br>                    // Compute new path cost<br>                    int newCost = curr.g + grid[nr][nc];<br><br>                    // Update if shorter path found<br>                    if (newCost &lt; dist[nr][nc]) {<br><br>                        dist[nr][nc] = newCost;<br><br>                        int h =<br>                                heuristic(<br>                                        nr,<br>                                        nc,<br>                                        rows - 1,<br>                                        cols - 1<br>                                );<br><br>                        // Add updated node to queue<br>                        pq.offer(<br>                                new Node(<br>                                        nr,<br>                                        nc,<br>                                        newCost,<br>                                        newCost + h<br>                                )<br>                        );<br>                    }<br>                }<br>            }<br>        }<br><br>        // Goal unreachable<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[][] grid = {<br>                {1, 3, 1},<br>                {1, 5, 1},<br>                {4, 2, 1}<br>        };<br><br>        int result = aStar(grid);<br><br>        System.out.println(&quot;Minimum path cost: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum path cost: 5</pre><p>This implementation extends the traditional grid-based version of A* by allowing diagonal movement between cells. The Chebyshev distance heuristic is particularly effective in this scenario because it accurately reflects the minimum number of moves required when diagonal movement is available.</p><h4>4. Tree Implementation — Depth-Based Heuristic</h4><p>A* can also be applied to tree structures, where each node represents a state and each edge represents a decision or transition. Unlike general graphs, trees do not contain cycles, meaning each node has a single unique path from the root. This simplifies the search process because the algorithm does not need to handle repeated states or revisit previously explored nodes.</p><p>In this implementation, the heuristic is based on the estimated remaining depth to the goal. Since tree structures are naturally hierarchical, nodes that are closer in depth are often closer to the target as well. This provides a simple and effective way to guide the search without requiring more complex distance calculations.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Represents a node stored in the priority queue<br>    static class Node {<br>        TreeNode treeNode; // Reference to the tree node<br>        int g; // Actual cost from the root node<br>        int f; // Estimated total cost (g + h)<br><br>        // Constructor to initialize node values<br>        Node(TreeNode treeNode, int g, int f) {<br>            this.treeNode = treeNode;<br>            this.g = g;<br>            this.f = f;<br>        }<br>    }<br><br>    // Represents a node in the tree<br>    static class TreeNode {<br>        String name; // Node identifier<br><br>        // Estimated remaining depth to the goal<br>        int estimatedDepthToGoal;<br><br>        // List of child connections<br>        List&lt;TreeEdge&gt; children = new ArrayList&lt;&gt;();<br><br>        // Constructor to initialize tree node<br>        TreeNode(String name, int estimatedDepthToGoal) {<br>            this.name = name;<br>            this.estimatedDepthToGoal = estimatedDepthToGoal;<br>        }<br>    }<br><br>    // Represents a connection between tree nodes<br>    static class TreeEdge {<br>        TreeNode to; // Child node<br>        int cost; // Cost to move to child node<br><br>        // Constructor to initialize edge<br>        TreeEdge(TreeNode to, int cost) {<br>            this.to = to;<br>            this.cost = cost;<br>        }<br>    }<br><br>    // Depth-based heuristic function<br>    // Estimates how far the node is from the goal<br>    static int heuristic(TreeNode node) {<br>        return node.estimatedDepthToGoal;<br>    }<br><br>    // A* search algorithm for a tree structure<br>    public static int aStar(TreeNode root, String goal) {<br><br>        // Priority queue ordered by lowest estimated total cost<br>        PriorityQueue&lt;Node&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(n -&gt; n.f));<br><br>        // Add root node to the priority queue<br>        pq.offer(<br>                new Node(<br>                        root,<br>                        0, // Initial path cost<br>                        heuristic(root) // Initial estimated total cost<br>                )<br>        );<br><br>        // Continue searching while nodes remain<br>        while (!pq.isEmpty()) {<br><br>            // Get node with the smallest f value<br>            Node curr = pq.poll();<br><br>            // If goal node is reached, return total path cost<br>            if (curr.treeNode.name.equals(goal)) {<br>                return curr.g;<br>            }<br><br>            // Explore all child nodes<br>            for (TreeEdge edge : curr.treeNode.children) {<br><br>                // Compute new path cost to child node<br>                int newCost = curr.g + edge.cost;<br><br>                // Compute heuristic estimate for child node<br>                int h = heuristic(edge.to);<br><br>                // Add child node to priority queue<br>                pq.offer(<br>                        new Node(<br>                                edge.to,<br>                                newCost,<br>                                newCost + h // f = g + h<br>                        )<br>                );<br>            }<br>        }<br><br>        // Return -1 if goal cannot be reached<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Create tree nodes with estimated depth values<br>        TreeNode root = new TreeNode(&quot;A&quot;, 2);<br>        TreeNode b = new TreeNode(&quot;B&quot;, 1);<br>        TreeNode c = new TreeNode(&quot;C&quot;, 1);<br>        TreeNode d = new TreeNode(&quot;D&quot;, 0);<br><br>        // Add child connections from root<br>        root.children.add(new TreeEdge(b, 2));<br>        root.children.add(new TreeEdge(c, 3));<br><br>        // Add child connection from B to D<br>        b.children.add(new TreeEdge(d, 2));<br><br>        // Run A* search from root node to goal node D<br>        int result = aStar(root, &quot;D&quot;);<br><br>        // Print minimum path cost<br>        System.out.println(&quot;Minimum path cost: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum path cost: 4</pre><p>This tree-based version demonstrates how A* can be adapted to hierarchical search problems by combining the actual path cost with an estimate of the remaining depth to the goal. While tree-based A* is less common than grid or graph pathfinding, it is useful in areas such as AI decision trees, game behavior planning, and other structured search problems where states are organized hierarchically.</p><h4>5. Continuous Space / Navigation Meshes — Euclidean Distance</h4><p>A* can be applied to continuous spaces, where movement is not restricted to fixed grid cells or discrete graph steps. Instead, objects can move freely in any direction through an environment. This type of pathfinding is commonly used in robotics, 3D games, autonomous vehicles, and drone navigation.</p><p>Rather than using a regular grid, these systems often represent the environment using navigation meshes (NavMesh), waypoint systems, or polygon-based movement areas. In these representations, nodes typically correspond to positions or regions in continuous space, allowing more natural and realistic movement.</p><p>Because movement is unrestricted and can occur in any direction, the <strong>Euclidean distance</strong> heuristic is usually the most appropriate choice. It estimates the direct straight-line distance between the current position and the goal. This heuristic works well in continuous environments because it closely approximates the true shortest path when movement is free in all directions. Unlike Manhattan or Chebyshev distance, Euclidean distance naturally reflects real geometric movement in open spaces.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Represents a position in continuous 2D space<br>    static class Point {<br>        double x, y;<br><br>        // Constructor to initialize coordinates<br>        Point(double x, double y) {<br>            this.x = x;<br>            this.y = y;<br>        }<br>    }<br><br>    // Represents a node used in the priority queue<br>    static class Node {<br>        String name;<br>        double g; // Actual cost from start<br>        double f; // Estimated total cost (g + h)<br><br>        // Constructor to initialize node values<br>        Node(String name, double g, double f) {<br>            this.name = name;<br>            this.g = g;<br>            this.f = f;<br>        }<br>    }<br><br>    // Represents a connection between nodes<br>    static class Edge {<br>        String to;<br>        double cost;<br><br>        // Constructor to initialize edge<br>        Edge(String to, double cost) {<br>            this.to = to;<br>            this.cost = cost;<br>        }<br>    }<br><br>    // Stores coordinates for each node<br>    static Map&lt;String, Point&gt; positions = new HashMap&lt;&gt;();<br><br>    // Euclidean distance heuristic<br>    static double heuristic(String node, String goal) {<br><br>        Point a = positions.get(node);<br>        Point b = positions.get(goal);<br><br>        return Math.sqrt(<br>                Math.pow(a.x - b.x, 2) +<br>                Math.pow(a.y - b.y, 2)<br>        );<br>    }<br><br>    // A* search algorithm<br>    public static double aStar(<br>            Map&lt;String, List&lt;Edge&gt;&gt; graph,<br>            String start,<br>            String goal<br>    ) {<br><br>        // Stores shortest known distance to each node<br>        Map&lt;String, Double&gt; dist = new HashMap&lt;&gt;();<br><br>        // Priority queue ordered by lowest estimated cost<br>        PriorityQueue&lt;Node&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingDouble(n -&gt; n.f));<br><br>        // Initialize all distances as infinity<br>        for (String node : graph.keySet()) {<br>            dist.put(node, Double.MAX_VALUE);<br>        }<br><br>        // Distance to start node is 0<br>        dist.put(start, 0.0);<br><br>        // Add start node to priority queue<br>        pq.offer(<br>                new Node(<br>                        start,<br>                        0.0,<br>                        heuristic(start, goal)<br>                )<br>        );<br><br>        // Continue searching while nodes remain<br>        while (!pq.isEmpty()) {<br><br>            // Get node with smallest estimated total cost<br>            Node curr = pq.poll();<br><br>            // Goal reached<br>            if (curr.name.equals(goal)) {<br>                return curr.g;<br>            }<br><br>            // Explore neighboring nodes<br>            for (Edge edge : graph.get(curr.name)) {<br><br>                // Compute new path cost<br>                double newCost = curr.g + edge.cost;<br><br>                // Update if shorter path found<br>                if (newCost &lt; dist.get(edge.to)) {<br><br>                    dist.put(edge.to, newCost);<br><br>                    double h = heuristic(edge.to, goal);<br><br>                    // Add updated node to queue<br>                    pq.offer(<br>                            new Node(<br>                                    edge.to,<br>                                    newCost,<br>                                    newCost + h<br>                            )<br>                    );<br>                }<br>            }<br>        }<br><br>        // Goal unreachable<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Graph representing movement in continuous space<br>        Map&lt;String, List&lt;Edge&gt;&gt; graph = new HashMap&lt;&gt;();<br><br>        // Positions of nodes in 2D space<br>        positions.put(&quot;A&quot;, new Point(0.0, 0.0));<br>        positions.put(&quot;B&quot;, new Point(2.5, 1.0));<br>        positions.put(&quot;C&quot;, new Point(4.0, 3.0));<br>        positions.put(&quot;D&quot;, new Point(6.0, 4.5));<br><br>        // Connections between nodes<br>        graph.put(&quot;A&quot;, List.of(<br>                new Edge(&quot;B&quot;, 2.7),<br>                new Edge(&quot;C&quot;, 5.0)<br>        ));<br><br>        graph.put(&quot;B&quot;, List.of(<br>                new Edge(&quot;C&quot;, 2.0),<br>                new Edge(&quot;D&quot;, 4.2)<br>        ));<br><br>        graph.put(&quot;C&quot;, List.of(<br>                new Edge(&quot;D&quot;, 1.8)<br>        ));<br><br>        graph.put(&quot;D&quot;, List.of());<br><br>        // Run A* search<br>        double result = aStar(graph, &quot;A&quot;, &quot;D&quot;);<br><br>        // Print minimum path cost<br>        System.out.println(&quot;Minimum path cost: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum path cost: 6.8</pre><p>This continuous-space version of A* demonstrates how the algorithm can operate in environments where movement is not limited to fixed grid directions. By using Euclidean distance as the heuristic, the search is guided toward the goal using the direct geometric distance between positions, making it especially effective for realistic navigation and free-form movement systems.</p><h4>6. A* Path Reconstruction</h4><p>In many real-world systems, finding the minimum cost alone is not enough — we also need the actual sequence of steps that forms the shortest path.</p><p>To support this, A* stores a reference to each node’s parent whenever a better path is discovered. After reaching the destination, these parent pointers allow the algorithm to reconstruct the path by walking backward from the goal to the start.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    static class Node {<br><br>        int row, col;<br>        int g, f; // g = actual cost so far, f = estimated total cost<br><br>        Node(int row, int col, int g, int f) {<br>            this.row = row;<br>            this.col = col;<br>            this.g = g;<br>            this.f = f;<br>        }<br>    }<br><br>    // Manhattan distance heuristic<br>    static int heuristic(int r, int c, int targetRow, int targetCol) {<br>        return Math.abs(r - targetRow) + Math.abs(c - targetCol);<br>    }<br><br>    public static List&lt;int[]&gt; shortestPath(int[][] grid) {<br><br>        int rows = grid.length;<br>        int cols = grid[0].length;<br><br>        // Stores the best known cost to reach each cell<br>        int[][] dist = new int[rows][cols];<br><br>        for (int[] row : dist) {<br>            Arrays.fill(row, Integer.MAX_VALUE);<br>        }<br><br>        // Parent pointers used to reconstruct the final path<br>        int[][] parentRow = new int[rows][cols];<br>        int[][] parentCol = new int[rows][cols];<br><br>        // Initialize parents as &quot;unknown&quot;<br>        for (int[] row : parentRow) {<br>            Arrays.fill(row, -1);<br>        }<br>        for (int[] row : parentCol) {<br>            Arrays.fill(row, -1);<br>        }<br><br>        // Movement directions (4-directional grid)<br>        int[][] dirs = {<br>                {1, 0},<br>                {-1, 0},<br>                {0, 1},<br>                {0, -1}<br>        };<br><br>        // Priority queue ensures we always expand the most promising node first<br>        PriorityQueue&lt;Node&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(n -&gt; n.f));<br><br>        // Initialize start node (top-left corner)<br>        dist[0][0] = grid[0][0];<br><br>        pq.offer(<br>                new Node(<br>                        0,<br>                        0,<br>                        grid[0][0], // g cost<br>                        grid[0][0] + heuristic(0, 0, rows - 1, cols - 1) // f = g + h<br>                )<br>        );<br><br>        while (!pq.isEmpty()) {<br><br>            Node curr = pq.poll();<br><br>            int r = curr.row;<br>            int c = curr.col;<br><br>            // Stop early if we reach the goal node<br>            if (r == rows - 1 &amp;&amp; c == cols - 1) {<br>                break;<br>            }<br><br>            // Explore all neighboring cells<br>            for (int[] d : dirs) {<br><br>                int nr = r + d[0];<br>                int nc = c + d[1];<br><br>                // Skip invalid positions<br>                if (nr &gt;= 0 &amp;&amp; nc &gt;= 0 &amp;&amp; nr &lt; rows &amp;&amp; nc &lt; cols) {<br><br>                    // Compute cost of reaching this neighbor through current node<br>                    int newCost = curr.g + grid[nr][nc];<br><br>                    // Only update if this path is better than any previous one<br>                    if (newCost &lt; dist[nr][nc]) {<br><br>                        dist[nr][nc] = newCost;<br><br>                        // Record where we came from (for path reconstruction)<br>                        parentRow[nr][nc] = r;<br>                        parentCol[nr][nc] = c;<br><br>                        int h = heuristic(nr, nc, rows - 1, cols - 1);<br><br>                        // Push updated node into priority queue<br>                        pq.offer(<br>                                new Node(<br>                                        nr,<br>                                        nc,<br>                                        newCost,<br>                                        newCost + h<br>                                )<br>                        );<br>                    }<br>                }<br>            }<br>        }<br><br>        // Reconstruct path by walking backwards from destination<br>        List&lt;int[]&gt; path = new ArrayList&lt;&gt;();<br><br>        int r = rows - 1;<br>        int c = cols - 1;<br><br>        // Follow parent pointers until reaching the start (-1, -1)<br>        while (r != -1 &amp;&amp; c != -1) {<br><br>            path.add(new int[]{r, c});<br><br>            int pr = parentRow[r][c];<br>            int pc = parentCol[r][c];<br><br>            r = pr;<br>            c = pc;<br>        }<br><br>        // Reverse because we built the path from goal → start<br>        Collections.reverse(path);<br><br>        return path;<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[][] grid = {<br>                {1, 3, 1},<br>                {1, 5, 1},<br>                {4, 2, 1}<br>        };<br><br>        List&lt;int[]&gt; path = shortestPath(grid);<br><br>        System.out.println(&quot;Shortest Path:&quot;);<br><br>        for (int[] cell : path) {<br>            System.out.println(&quot;(&quot; + cell[0] + &quot;, &quot; + cell[1] + &quot;)&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Shortest Path:<br>// (0, 0)<br>// (0, 1)<br>// (0, 2)<br>// (1, 2)<br>// (2, 2)</pre><p>This extension turns A* from a cost calculator into a full path reconstruction algorithm. Instead of only telling you <em>how expensive the optimal route is</em>, it now reveals <em>exactly which steps to take to follow that route</em> — which is what most real-world systems actually need.</p><h3>Practical Examples 💡</h3><p>A* is widely used in real-world systems because it provides an excellent balance between optimality and efficiency. Rather than exploring every possible path, it uses a heuristic to focus the search toward the most promising routes, significantly reducing the amount of work required to reach a solution.</p><p>Although the underlying algorithm remains the same, the meaning of nodes, edges, and movement costs varies depending on the problem being solved. The following sections demonstrate some of the most common applications of A*.</p><h4>1. Video Game AI</h4><p>A* is one of the most widely used pathfinding algorithms in game development. It enables players, enemies, and non-player characters (NPCs) to navigate around obstacles, avoid dangerous terrain, and efficiently move toward objectives.</p><p>A typical game world is represented as a grid where walkable tiles become nodes and blocked tiles become obstacles. A* searches this grid and returns the optimal route from the starting position to the destination.</p><pre>import java.util.*;<br><br>record Node(int x, int y) {}<br><br>class AStar {<br><br>    private static class PathNode {<br>        Node node;<br>        PathNode parent;<br>        int g; // Cost from start<br>        int h; // Heuristic cost to goal<br><br>        PathNode(Node node, PathNode parent, int g, int h) {<br>            this.node = node;<br>            this.parent = parent;<br>            this.g = g;<br>            this.h = h;<br>        }<br><br>        int f() {<br>            return g + h;<br>        }<br>    }<br><br>    public static List&lt;Node&gt; findPath(<br>            int[][] map,<br>            Node start,<br>            Node goal) {<br><br>        PriorityQueue&lt;PathNode&gt; openSet =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(PathNode::f));<br><br>        Map&lt;Node, Integer&gt; gScores = new HashMap&lt;&gt;();<br>        Set&lt;Node&gt; closedSet = new HashSet&lt;&gt;();<br><br>        openSet.add(<br>                new PathNode(<br>                        start,<br>                        null,<br>                        0,<br>                        heuristic(start, goal)<br>                )<br>        );<br><br>        gScores.put(start, 0);<br><br>        while (!openSet.isEmpty()) {<br><br>            PathNode current = openSet.poll();<br><br>            if (current.node.equals(goal)) {<br>                return reconstructPath(current);<br>            }<br><br>            closedSet.add(current.node);<br><br>            for (Node neighbor : getNeighbors(map, current.node)) {<br><br>                if (closedSet.contains(neighbor)) {<br>                    continue;<br>                }<br><br>                int tentativeG = current.g + 1;<br><br>                if (tentativeG &lt; gScores.getOrDefault(neighbor, Integer.MAX_VALUE)) {<br><br>                    gScores.put(neighbor, tentativeG);<br><br>                    openSet.add(<br>                            new PathNode(<br>                                    neighbor,<br>                                    current,<br>                                    tentativeG,<br>                                    heuristic(neighbor, goal)<br>                            )<br>                    );<br>                }<br>            }<br>        }<br><br>        return Collections.emptyList();<br>    }<br><br>    private static int heuristic(Node a, Node b) {<br>        return Math.abs(a.x() - b.x())<br>                + Math.abs(a.y() - b.y());<br>    }<br><br>    private static List&lt;Node&gt; getNeighbors(<br>            int[][] map,<br>            Node node) {<br><br>        List&lt;Node&gt; neighbors = new ArrayList&lt;&gt;();<br><br>        int[][] directions = {<br>                {0, 1},<br>                {1, 0},<br>                {0, -1},<br>                {-1, 0}<br>        };<br><br>        for (int[] dir : directions) {<br><br>            int newX = node.x() + dir[0];<br>            int newY = node.y() + dir[1];<br><br>            if (newX &gt;= 0<br>                    &amp;&amp; newX &lt; map.length<br>                    &amp;&amp; newY &gt;= 0<br>                    &amp;&amp; newY &lt; map[0].length<br>                    &amp;&amp; map[newX][newY] == 0) {<br><br>                neighbors.add(new Node(newX, newY));<br>            }<br>        }<br><br>        return neighbors;<br>    }<br><br>    private static List&lt;Node&gt; reconstructPath(<br>            PathNode goalNode) {<br><br>        List&lt;Node&gt; path = new ArrayList&lt;&gt;();<br><br>        PathNode current = goalNode;<br><br>        while (current != null) {<br>            path.add(current.node);<br>            current = current.parent;<br>        }<br><br>        Collections.reverse(path);<br><br>        return path;<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        int[][] map = {<br>                {0, 0, 0, 0},<br>                {1, 1, 0, 1},<br>                {0, 0, 0, 0},<br>                {0, 1, 1, 0}<br>        };<br><br>        Node start = new Node(0, 0);<br>        Node goal = new Node(3, 3);<br><br>        List&lt;Node&gt; path = AStar.findPath(map, start, goal);<br><br>        System.out.println(&quot;NPC path:&quot;);<br><br>        for (Node node : path) {<br>            System.out.printf(<br>                    &quot;(%d, %d)%n&quot;,<br>                    node.x(),<br>                    node.y()<br>            );<br>        }<br>    }<br>}<br><br>// NPC path:<br>// (0, 0)<br>// (1, 0)<br>// (2, 0)<br>// (2, 1)<br>// (2, 2)<br>// (2, 3)<br>// (3, 3)</pre><p>The NPC can then follow the generated path one step at a time. In modern games, A* is frequently combined with path smoothing, navigation meshes, and path caching to improve performance.</p><h4>2. Robotics</h4><p>In robotics, A* is used to plan safe and efficient movement through physical environments. Unlike many game maps, movement costs are often weighted to reflect real-world constraints such as energy consumption, terrain difficulty, or risk.</p><p>For example, a warehouse robot may choose a slightly longer route if it requires less energy or avoids congested areas.</p><pre>import java.util.*;<br><br>record Node(int x, int y) {}<br><br>class AStar {<br><br>    private static class PathNode {<br>        Node node;<br>        PathNode parent;<br>        int g; // Total terrain cost so far<br>        int h; // Heuristic estimate<br><br>        PathNode(Node node, PathNode parent, int g, int h) {<br>            this.node = node;<br>            this.parent = parent;<br>            this.g = g;<br>            this.h = h;<br>        }<br><br>        int f() {<br>            return g + h;<br>        }<br>    }<br><br>    public static List&lt;Node&gt; findLowestCostPath(<br>            int[][] terrain,<br>            Node start,<br>            Node goal) {<br><br>        PriorityQueue&lt;PathNode&gt; openSet =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(PathNode::f));<br><br>        Map&lt;Node, Integer&gt; costs = new HashMap&lt;&gt;();<br>        Set&lt;Node&gt; closedSet = new HashSet&lt;&gt;();<br><br>        openSet.add(<br>                new PathNode(<br>                        start,<br>                        null,<br>                        0,<br>                        heuristic(start, goal)<br>                )<br>        );<br><br>        costs.put(start, 0);<br><br>        while (!openSet.isEmpty()) {<br><br>            PathNode current = openSet.poll();<br><br>            if (current.node.equals(goal)) {<br>                return reconstructPath(current);<br>            }<br><br>            if (!closedSet.add(current.node)) {<br>                continue;<br>            }<br><br>            for (Node neighbor :<br>                    getNeighbors(terrain, current.node)) {<br><br>                int movementCost =<br>                        terrain[neighbor.x()][neighbor.y()];<br><br>                int tentativeCost =<br>                        current.g + movementCost;<br><br>                if (tentativeCost &lt;<br>                        costs.getOrDefault(<br>                                neighbor,<br>                                Integer.MAX_VALUE)) {<br><br>                    costs.put(neighbor, tentativeCost);<br><br>                    openSet.add(<br>                            new PathNode(<br>                                    neighbor,<br>                                    current,<br>                                    tentativeCost,<br>                                    heuristic(<br>                                            neighbor,<br>                                            goal<br>                                    )<br>                            )<br>                    );<br>                }<br>            }<br>        }<br><br>        return Collections.emptyList();<br>    }<br><br>    private static int heuristic(<br>            Node current,<br>            Node goal) {<br><br>        return Math.abs(current.x() - goal.x())<br>                + Math.abs(current.y() - goal.y());<br>    }<br><br>    private static List&lt;Node&gt; getNeighbors(<br>            int[][] terrain,<br>            Node node) {<br><br>        List&lt;Node&gt; neighbors = new ArrayList&lt;&gt;();<br><br>        int[][] directions = {<br>                {0, 1},<br>                {1, 0},<br>                {0, -1},<br>                {-1, 0}<br>        };<br><br>        for (int[] direction : directions) {<br><br>            int x = node.x() + direction[0];<br>            int y = node.y() + direction[1];<br><br>            if (x &gt;= 0<br>                    &amp;&amp; x &lt; terrain.length<br>                    &amp;&amp; y &gt;= 0<br>                    &amp;&amp; y &lt; terrain[0].length) {<br><br>                neighbors.add(new Node(x, y));<br>            }<br>        }<br><br>        return neighbors;<br>    }<br><br>    private static List&lt;Node&gt; reconstructPath(<br>            PathNode goalNode) {<br><br>        List&lt;Node&gt; path = new ArrayList&lt;&gt;();<br><br>        PathNode current = goalNode;<br><br>        while (current != null) {<br>            path.add(current.node);<br>            current = current.parent;<br>        }<br><br>        Collections.reverse(path);<br><br>        return path;<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        int[][] terrain = {<br>                {1, 1, 2, 5},<br>                {1, 3, 2, 1},<br>                {4, 2, 1, 1},<br>                {5, 5, 1, 1}<br>        };<br><br>        Node start = new Node(0, 0);<br>        Node goal = new Node(3, 3);<br><br>        List&lt;Node&gt; path =<br>                AStar.findLowestCostPath(<br>                        terrain,<br>                        start,<br>                        goal<br>                );<br><br>        System.out.println(<br>                &quot;Energy-efficient route:&quot;<br>        );<br><br>        path.forEach(System.out::println);<br>    }<br>}<br><br>// Energy-efficient route:<br>// Node[x=0, y=0]<br>// Node[x=0, y=1]<br>// Node[x=0, y=2]<br>// Node[x=1, y=2]<br>// Node[x=1, y=3]<br>// Node[x=2, y=3]<br>// Node[x=3, y=3]</pre><p>In this example, each value represents the energy cost required to enter a location. Rather than minimizing distance alone, A* minimizes the total traversal cost.</p><p>Common applications include warehouse automation, autonomous vehicles, drones, and industrial robotics.</p><h4>3. GPS Navigation Systems</h4><p>GPS navigation systems use the same core principles as grid-based pathfinding, but the graph represents a road network rather than a game map. In this context:</p><ul><li>Nodes represent intersections.</li><li>Edges represent roads.</li><li>Edge costs may represent distance, travel time, fuel consumption, or traffic conditions.</li></ul><p>A* uses the known cost of roads together with a heuristic estimate of the remaining distance to the destination. This allows navigation systems to compute routes efficiently across extremely large networks.</p><p>Conceptually, the process is identical to the game example:</p><pre>import java.util.*;<br><br>record Location(<br>        String name,<br>        int x,<br>        int y) {<br>}<br><br>record Road(<br>        String destination,<br>        int distance) {<br>}<br><br>class RoadGraph {<br><br>    private final Map&lt;String, Location&gt; locations =<br>            new HashMap&lt;&gt;();<br><br>    private final Map&lt;String, List&lt;Road&gt;&gt; roads =<br>            new HashMap&lt;&gt;();<br><br>    public void addLocation(Location location) {<br><br>        locations.put(<br>                location.name(),<br>                location<br>        );<br><br>        roads.putIfAbsent(<br>                location.name(),<br>                new ArrayList&lt;&gt;()<br>        );<br>    }<br><br>    public void addRoad(<br>            String from,<br>            String to,<br>            int distance) {<br><br>        roads.get(from)<br>                .add(new Road(to, distance));<br><br>        roads.get(to)<br>                .add(new Road(from, distance));<br>    }<br><br>    public List&lt;Road&gt; getNeighbors(<br>            String location) {<br><br>        return roads.getOrDefault(<br>                location,<br>                Collections.emptyList()<br>        );<br>    }<br><br>    public Location getLocation(<br>            String name) {<br><br>        return locations.get(name);<br>    }<br>}<br><br>class AStar {<br><br>    private static class PathNode {<br><br>        String location;<br>        PathNode parent;<br>        int g;<br>        int h;<br><br>        PathNode(<br>                String location,<br>                PathNode parent,<br>                int g,<br>                int h) {<br><br>            this.location = location;<br>            this.parent = parent;<br>            this.g = g;<br>            this.h = h;<br>        }<br><br>        int f() {<br>            return g + h;<br>        }<br>    }<br><br>    public static List&lt;String&gt; findRoute(<br>            RoadGraph graph,<br>            String start,<br>            String goal) {<br><br>        PriorityQueue&lt;PathNode&gt; openSet =<br>                new PriorityQueue&lt;&gt;(<br>                        Comparator.comparingInt(<br>                                PathNode::f<br>                        )<br>                );<br><br>        Map&lt;String, Integer&gt; gScores =<br>                new HashMap&lt;&gt;();<br><br>        Set&lt;String&gt; closedSet =<br>                new HashSet&lt;&gt;();<br><br>        openSet.add(<br>                new PathNode(<br>                        start,<br>                        null,<br>                        0,<br>                        heuristic(<br>                                graph,<br>                                start,<br>                                goal<br>                        )<br>                )<br>        );<br><br>        gScores.put(start, 0);<br><br>        while (!openSet.isEmpty()) {<br><br>            PathNode current =<br>                    openSet.poll();<br><br>            if (current.location.equals(goal)) {<br>                return reconstructPath(<br>                        current<br>                );<br>            }<br><br>            if (!closedSet.add(<br>                    current.location)) {<br>                continue;<br>            }<br><br>            for (Road road :<br>                    graph.getNeighbors(<br>                            current.location)) {<br><br>                String neighbor =<br>                        road.destination();<br><br>                int tentativeG =<br>                        current.g<br>                                + road.distance();<br><br>                if (tentativeG &lt;<br>                        gScores.getOrDefault(<br>                                neighbor,<br>                                Integer.MAX_VALUE)) {<br><br>                    gScores.put(<br>                            neighbor,<br>                            tentativeG<br>                    );<br><br>                    openSet.add(<br>                            new PathNode(<br>                                    neighbor,<br>                                    current,<br>                                    tentativeG,<br>                                    heuristic(<br>                                            graph,<br>                                            neighbor,<br>                                            goal<br>                                    )<br>                            )<br>                    );<br>                }<br>            }<br>        }<br><br>        return Collections.emptyList();<br>    }<br><br>    private static int heuristic(<br>            RoadGraph graph,<br>            String current,<br>            String goal) {<br><br>        Location currentLocation =<br>                graph.getLocation(current);<br><br>        Location goalLocation =<br>                graph.getLocation(goal);<br><br>        double dx =<br>                currentLocation.x()<br>                        - goalLocation.x();<br><br>        double dy =<br>                currentLocation.y()<br>                        - goalLocation.y();<br><br>        return (int) Math.sqrt(<br>                dx * dx + dy * dy<br>        );<br>    }<br><br>    private static List&lt;String&gt; reconstructPath(<br>            PathNode goalNode) {<br><br>        List&lt;String&gt; path =<br>                new ArrayList&lt;&gt;();<br><br>        PathNode current =<br>                goalNode;<br><br>        while (current != null) {<br><br>            path.add(<br>                    current.location<br>            );<br><br>            current =<br>                    current.parent;<br>        }<br><br>        Collections.reverse(path);<br><br>        return path;<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        RoadGraph graph =<br>               new RoadGraph();<br><br>        graph.addLocation(<br>                new Location(<br>                        &quot;Home&quot;,<br>                        0,<br>                        0<br>                )<br>        );<br><br>        graph.addLocation(<br>                new Location(<br>                        &quot;Highway&quot;,<br>                        4,<br>                        3<br>                )<br>        );<br><br>        graph.addLocation(<br>                new Location(<br>                        &quot;Office&quot;,<br>                        10,<br>                        0<br>                )<br>        );<br><br>        graph.addRoad(<br>                &quot;Home&quot;,<br>                &quot;Highway&quot;,<br>                5<br>        );<br><br>        graph.addRoad(<br>                &quot;Highway&quot;,<br>                &quot;Office&quot;,<br>                10<br>        );<br><br>        graph.addRoad(<br>                &quot;Home&quot;,<br>                &quot;Office&quot;,<br>                20<br>        );<br><br>        List&lt;String&gt; route =<br>                AStar.findRoute(<br>                        graph,<br>                        &quot;Home&quot;,<br>                        &quot;Office&quot;<br>                );<br><br>        System.out.println(<br>                &quot;Best route: &quot;<br>                        + route<br>        );<br>    }<br>}<br><br>// Best route: [Home, Highway, Office]</pre><p>The difference lies in how the graph is constructed and how movement costs are calculated. Real navigation systems further incorporate live traffic updates, speed limits, road closures, and historical congestion data.</p><h4>4. Puzzle Solving</h4><p>A* is also widely used to solve state-space search problems such as the 8-puzzle, 15-puzzle, maze solving, and Sokoban.</p><p>In these problems, each node represents an entire puzzle configuration rather than a physical location. A move transforms one state into another, creating a graph of possible solutions.</p><p>The heuristic estimates how close the current state is to the goal state, allowing A* to prioritize promising configurations.</p><pre>import java.util.*;<br><br>record PuzzleState(<br>        int[][] board,<br>        int moves) {<br>}<br><br>class AStar {<br><br>    private static class Node {<br><br>        int[][] board;<br>        int moves;<br>        int heuristic;<br>        Node parent;<br><br>        Node(<br>                int[][] board,<br>                int moves,<br>                int heuristic,<br>                Node parent) {<br><br>            this.board = board;<br>            this.moves = moves;<br>            this.heuristic = heuristic;<br>            this.parent = parent;<br>        }<br><br>        int f() {<br>            return moves + heuristic;<br>        }<br>    }<br><br>    public static PuzzleState solve(<br>            int[][] start,<br>            int[][] goal) {<br><br>        PriorityQueue&lt;Node&gt; openSet =<br>                new PriorityQueue&lt;&gt;(<br>                        Comparator.comparingInt(<br>                                Node::f<br>                        )<br>                );<br><br>        Set&lt;String&gt; visited =<br>                new HashSet&lt;&gt;();<br><br>        openSet.add(<br>                new Node(<br>                        copyBoard(start),<br>                        0,<br>                        heuristic(start, goal),<br>                        null<br>                )<br>        );<br><br>        while (!openSet.isEmpty()) {<br><br>            Node current =<br>                    openSet.poll();<br><br>            String key =<br>                    serialize(current.board);<br><br>            if (!visited.add(key)) {<br>                continue;<br>            }<br><br>            if (Arrays.deepEquals(<br>                    current.board,<br>                    goal)) {<br><br>                return new PuzzleState(<br>                        current.board,<br>                        current.moves<br>                );<br>            }<br><br>            for (int[][] neighbor :<br>                    generateNeighbors(<br>                            current.board)) {<br><br>                if (!visited.contains(<br>                        serialize(neighbor))) {<br><br>                    openSet.add(<br>                            new Node(<br>                                    neighbor,<br>                                    current.moves + 1,<br>                                    heuristic(<br>                                            neighbor,<br>                                            goal<br>                                    ),<br>                                    current<br>                            )<br>                    );<br>                }<br>            }<br>        }<br><br>        return null;<br>    }<br><br>    private static int heuristic(<br>            int[][] board,<br>            int[][] goal) {<br><br>        int distance = 0;<br><br>        for (int row = 0;<br>             row &lt; board.length;<br>             row++) {<br><br>            for (int col = 0;<br>                 col &lt; board[row].length;<br>                 col++) {<br><br>                int value =<br>                        board[row][col];<br><br>                if (value == 0) {<br>                    continue;<br>                }<br><br>                for (int goalRow = 0;<br>                     goalRow &lt; goal.length;<br>                     goalRow++) {<br><br>                    for (int goalCol = 0;<br>                         goalCol &lt; goal[goalRow].length;<br>                         goalCol++) {<br><br>                        if (goal[goalRow][goalCol]<br>                                == value) {<br><br>                            distance += Math.abs(<br>                                    row - goalRow<br>                            );<br><br>                            distance += Math.abs(<br>                                    col - goalCol<br>                            );<br>                        }<br>                    }<br>                }<br>            }<br>        }<br><br>        return distance;<br>    }<br><br>    private static List&lt;int[][]&gt;<br>    generateNeighbors(<br>            int[][] board) {<br><br>        List&lt;int[][]&gt; neighbors =<br>                new ArrayList&lt;&gt;();<br><br>        int emptyRow = -1;<br>        int emptyCol = -1;<br><br>        for (int row = 0;<br>             row &lt; board.length;<br>             row++) {<br><br>            for (int col = 0;<br>                 col &lt; board[row].length;<br>                 col++) {<br><br>                if (board[row][col] == 0) {<br>                    emptyRow = row;<br>                    emptyCol = col;<br>                }<br>            }<br>        }<br><br>        int[][] directions = {<br>                {-1, 0},<br>                {1, 0},<br>                {0, -1},<br>                {0, 1}<br>        };<br><br>        for (int[] direction :<br>                directions) {<br><br>            int newRow =<br>                    emptyRow + direction[0];<br><br>            int newCol =<br>                    emptyCol + direction[1];<br><br>            if (newRow &gt;= 0<br>                    &amp;&amp; newRow &lt; 3<br>                    &amp;&amp; newCol &gt;= 0<br>                    &amp;&amp; newCol &lt; 3) {<br><br>                int[][] copy =<br>                        copyBoard(board);<br><br>                copy[emptyRow][emptyCol] =<br>                        copy[newRow][newCol];<br><br>                copy[newRow][newCol] = 0;<br><br>                neighbors.add(copy);<br>            }<br>        }<br><br>        return neighbors;<br>    }<br><br>    private static String serialize(<br>            int[][] board) {<br><br>        StringBuilder builder =<br>                new StringBuilder();<br><br>        for (int[] row : board) {<br><br>            for (int value : row) {<br>                builder.append(value);<br>            }<br>        }<br><br>        return builder.toString();<br>    }<br><br>    private static int[][] copyBoard(<br>            int[][] board) {<br><br>        int[][] copy =<br>                new int[board.length]<br>                        [board[0].length];<br><br>        for (int i = 0;<br>             i &lt; board.length;<br>             i++) {<br><br>            copy[i] =<br>                    board[i].clone();<br>        }<br><br>        return copy;<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        int[][] start = {<br>                {1, 2, 3},<br>                {4, 0, 6},<br>                {7, 5, 8}<br>        };<br><br>        int[][] goal = {<br>                {1, 2, 3},<br>                {4, 5, 6},<br>                {7, 8, 0}<br>        };<br><br>        PuzzleState solution =<br>                AStar.solve(<br>                        start,<br>                        goal<br>                );<br><br>        System.out.println(<br>                &quot;Moves required: &quot;<br>                        + solution.moves()<br>        );<br>    }<br>}<br><br>// Moves required: 2</pre><p>By using an informed heuristic, A* can dramatically reduce the number of states explored compared to uninformed search algorithms, making many otherwise intractable puzzles practical to solve.</p><h3>Conclusion 📣</h3><p>A* has earned its reputation as one of the most important pathfinding algorithms in computer science. By combining the actual cost of a path with a heuristic estimate of the remaining distance, it intelligently focuses its search on the most promising routes while still guaranteeing optimal solutions when an admissible heuristic is used.</p><p>Throughout this article, we’ve explored the core concepts behind A*, examined how its cost function works, implemented the algorithm in Java, and applied it to a variety of real-world scenarios. From guiding NPCs through game worlds and helping robots navigate complex environments to planning GPS routes and solving puzzles, A* demonstrates a remarkable balance between efficiency, flexibility, and accuracy.</p><p>While the algorithm has limitations — particularly in terms of memory consumption and heuristic design — it remains a foundational technique for pathfinding and graph traversal. Many modern navigation systems and AI applications still rely on A* directly or use algorithms derived from its principles.</p><p>Understanding A* provides more than just another algorithm for your toolkit. It introduces fundamental concepts such as informed search, heuristics, cost optimization, and graph exploration that appear throughout computer science and artificial intelligence. Whether you’re developing games, building autonomous systems, or simply studying algorithms, mastering A* offers valuable insight into how intelligent systems make decisions and find efficient solutions to complex problems.</p><p>Thanks for reading! Please give this article a like and follow me if you enjoyed it 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb070a8909a8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-algorithm-in-java-learn-with-practical-examples-bb070a8909a8">A* Algorithm in Java: Learn with Practical Examples</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dijkstra’s Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/dijkstras-algorithm-in-java-learn-with-practical-examples-9e7af310e466?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7af310e466</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[dijkstras-algorithm]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Sat, 16 May 2026 05:07:18 GMT</pubDate>
            <atom:updated>2026-05-16T05:07:18.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XyrwhNd5shpR-qoCFkIdA.png" /></figure><p>Dijkstra’s algorithm is one of the most widely used shortest-path algorithms in computer science. It calculates the minimum-cost path between nodes in a weighted graph, where each connection has an associated value such as distance, travel time, or network latency.</p><p>Because it can efficiently process graphs with varying edge weights, Dijkstra’s algorithm plays a critical role in systems such as GPS navigation, network routing, logistics planning, and AI pathfinding in games.</p><p>Created in 1956 by Dutch computer scientist <a href="https://en.wikipedia.org/wiki/Edsger_W._Dijkstra">Edsger W. Dijkstra</a>, the algorithm remains a fundamental concept in graph theory and software engineering.</p><p>At its core, the algorithm works by repeatedly selecting the node with the smallest known distance from the starting point and updating the distances of its neighboring nodes. Over time, this process produces the shortest possible paths to every reachable node in the graph.</p><p>In this article, we’ll break down how Dijkstra’s algorithm works, implement it step by step in Java, and explore practical examples that demonstrate where and why it is most effective.</p><h3>What Is Dijkstra’s Algorithm? 🔍</h3><p>Dijkstra’s algorithm finds the shortest path from a starting node to every other reachable node in a weighted graph with non-negative edge weights.</p><p>The algorithm works by continuously exploring the currently cheapest known path and improving distance estimates as better routes are discovered. Here is the code idea:</p><ol><li>Choose a starting node (source)</li><li>Assign a distance of 0 to the source node</li><li>Assign ∞ (infinity) to all other nodes</li><li>Select the unvisited node with the smallest known distance</li><li>Update the distances of its neighboring nodes if a shorter path is found</li><li>Repeat the process until all reachable nodes have been processed</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*15KkonMRnHdbzGhFw0PXCA.gif" /><figcaption>Animation of Djikstra Algorithm. <a href="https://commons.wikimedia.org/wiki/File:Dijkstra_Animation.gif">Ibmua</a>, Public domain, via Wikimedia Commons</figcaption></figure><p>In most implementations, Dijkstra’s algorithm uses a priority queue (commonly implemented as a min-heap) to efficiently retrieve the next closest node.</p><p>A useful way to visualize the algorithm is to imagine waves spreading outward from the source node. At each step, the algorithm expands through the lowest-cost reachable path, gradually building the shortest paths across the graph.</p><h3>When Should You Use Dijkstra’s Algorithm? 🧐</h3><p>Dijkstra’s algorithm is one of the most important algorithms for solving shortest path problems in weighted graphs. It is specifically designed for situations where traversal costs can vary between connections, but all edge weights remain non-negative.</p><p>In a graph, an edge weight represents the cost of moving from one node to another. Depending on the problem domain, this cost may represent:</p><ul><li>Distance</li><li>Travel time</li><li>Latency</li><li>Energy consumption</li><li>Risk</li><li>Resource usage</li></ul><p>Rather than minimizing the number of steps, Dijkstra’s algorithm minimizes the total accumulated cost required to reach a destination.</p><p>A key requirement of the algorithm is that all edge weights must be non-negative. A negative edge weight would reduce the total path cost after traversal, which breaks the algorithm’s core assumption that once the shortest path to a node has been finalized, it cannot later become smaller. Because of this, Dijkstra’s algorithm may produce incorrect results when negative-weight edges are present.</p><p>In practice, Dijkstra’s algorithm is useful whenever you need to determine the minimum-cost path through a connected system with varying traversal costs. Common applications include:</p><ul><li>Routing and navigation systems</li><li>Network communication</li><li>Weighted graph traversal</li><li>Grid-based pathfinding</li><li>Scheduling and optimization problems</li><li>Resource allocation systems</li></ul><p>When implemented with a priority queue, Dijkstra’s algorithm runs with a time complexity of <em>O((V + E) log V)</em>, where <em>V</em> = number of vertices and <em>E</em> = number of edges. Its space complexity is <em>O(V)</em>, since the algorithm must store shortest distances, visited states, and priority queue entries during execution.</p><h3>Limitations of Dijkstra’s Algorithm 📉</h3><p>Although Dijkstra’s algorithm is highly effective for many shortest-path problems, it also has several important limitations.</p><ul><li><strong>Does Not Support Negative Weights: </strong>Dijkstra’s algorithm assumes that all edge weights are non-negative. If a graph contains negative-weight edges, the algorithm can produce incorrect results because it relies on the assumption that once the shortest distance to a node is finalized, it cannot later become smaller. For graphs with negative weights, algorithms such as the Bellman–Ford algorithm are more appropriate.</li><li><strong>Performance on Uniform-Cost Graphs: </strong>When all edges have the same weight, the overhead of maintaining a priority queue may be unnecessary. In these cases, simpler graph traversal approaches can solve the problem more efficiently.</li><li><strong>Memory Usage in Large Graphs: </strong>In very large graphs, Dijkstra’s algorithm can consume significant memory because it must store distance information, visited states, and priority queue entries for many nodes during execution.</li><li><strong>Less Efficient Than Heuristic Search: </strong>In pathfinding systems where the destination is already known, heuristic-based algorithms such as A* can often perform better by directing the search toward the target instead of exploring outward uniformly.</li></ul><p>Despite these limitations, Dijkstra’s algorithm remains one of the foundational shortest-path algorithms in computer science. Its combination of correctness, efficiency, and practical applicability makes it an essential tool for graph traversal, routing systems, and pathfinding problems.</p><h3>From Theory to Practice 🛠️</h3><p>At its core, Dijkstra’s algorithm maintains the shortest known distance to each node while continuously exploring the most promising path available. A priority queue is typically used to efficiently select the next closest node, ensuring that smaller tentative distances are processed first.</p><p>As the graph is explored, the algorithm repeatedly performs a process called <em>relaxation</em>. Whenever a shorter path to a neighboring node is found, that node’s recorded distance is updated. Over time, these updates refine the solution until the shortest paths are fully determined.</p><p>Although implementations may differ across programming languages and data structures, the underlying idea remains the same: continuously improve distance estimates until the optimal paths are finalized. Let’s now see how this works in Java.</p><h4>1. Dijkstra Graph Implementation</h4><p>To understand how Dijkstra’s algorithm works in practice, let’s begin with a classic implementation using a weighted graph, an adjacency list, and a priority queue. The adjacency list efficiently stores graph connections, while the priority queue ensures that the algorithm always processes the node with the currently smallest known distance first.</p><p>This implementation follows the standard structure used in most real-world shortest path solutions and clearly demonstrates the core mechanics of distance updates, edge relaxation, and greedy node selection.</p><pre>import java.util.*;<br><br>// Represents a weighted edge in the graph<br>class Edge {<br>    int to;<br>    int weight;<br><br>    Edge(int to, int weight) {<br>        this.to = to;<br>        this.weight = weight;<br>    }<br>}<br><br>public class Main {<br><br>    // Dijkstra shortest path algorithm<br>    public static void dijkstra(List&lt;List&lt;Edge&gt;&gt; graph, int start) {<br><br>        int n = graph.size();<br><br>        // Stores shortest known distance to each node<br>        int[] dist = new int[n];<br><br>        // Initialize all distances to infinity<br>        Arrays.fill(dist, Integer.MAX_VALUE);<br><br>        // Distance to starting node is 0<br>        dist[start] = 0;<br><br>        // Min-heap priority queue:<br>        // each entry = {distance, node}<br>        PriorityQueue&lt;int[]&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(a -&gt; a[0]));<br><br>        // Start from source node<br>        pq.offer(new int[]{0, start});<br><br>        while (!pq.isEmpty()) {<br><br>            int[] current = pq.poll();<br><br>            int currentDist = current[0];<br>            int node = current[1];<br><br>            // Skip outdated queue entries<br>            if (currentDist &gt; dist[node]) continue;<br><br>            // Explore neighbors<br>            for (Edge edge : graph.get(node)) {<br><br>                int neighbor = edge.to;<br>                int weight = edge.weight;<br><br>                // Compute new candidate distance<br>                int newDist = dist[node] + weight;<br><br>                // Relaxation step:<br>                // update if shorter path found<br>                if (newDist &lt; dist[neighbor]) {<br><br>                    dist[neighbor] = newDist;<br><br>                    // Add updated distance to queue<br>                    pq.offer(new int[]{newDist, neighbor});<br>                }<br>            }<br>        }<br><br>        // Print shortest distances<br>        System.out.println(&quot;Shortest distances from node &quot; + start + &quot;:&quot;);<br><br>        for (int i = 0; i &lt; n; i++) {<br>            System.out.println(&quot;To &quot; + i + &quot; = &quot; + dist[i]);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        int n = 5;<br><br>        // Build weighted adjacency list<br>        List&lt;List&lt;Edge&gt;&gt; graph = new ArrayList&lt;&gt;();<br><br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        /*<br>                   4<br>              0 ------- 1<br>              |         | \<br>            1 |         |1 \ 2<br>              |         |   \<br>              2 ------- 3 --- 4<br>                   5       3<br>        */<br>        <br>        graph.get(0).add(new Edge(1, 4));<br>        graph.get(0).add(new Edge(2, 1));<br><br>        graph.get(2).add(new Edge(1, 2));<br>        graph.get(1).add(new Edge(3, 1));<br><br>        graph.get(2).add(new Edge(3, 5));<br>        graph.get(3).add(new Edge(4, 3));<br><br>        dijkstra(graph, 0);<br>    }<br>}<br><br>// Output:<br>// Shortest distances from node 0:<br>// To 0 = 0<br>// To 1 = 3<br>// To 2 = 1<br>// To 3 = 4<br>// To 4 = 7</pre><p>This example captures the fundamental principle behind Dijkstra’s algorithm: always expand the cheapest reachable node before exploring more expensive alternatives. By repeatedly selecting the node with the smallest tentative distance, the algorithm gradually refines its shortest path estimates until the optimal distances to all reachable nodes are determined.</p><p>The priority queue plays a critical role in maintaining efficiency, allowing the algorithm to process nodes in increasing order of their current shortest known distance. This greedy strategy is what enables Dijkstra’s algorithm to efficiently compute shortest paths across weighted graphs.</p><h4>2. Understanding Relaxation</h4><p>The core operation that drives Dijkstra’s algorithm is known as relaxation. Every time the algorithm explores an edge, it checks whether traveling through the current node produces a shorter path to a neighboring node than any path discovered so far.</p><p>In simpler terms, the algorithm repeatedly asks: <em>“Does this newly discovered path improve the best known distance?”. </em>If the answer is yes, the algorithm updates the neighbor’s distance with the smaller value and continues exploring from there.</p><p>Mathematically, relaxation is performed using the following comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*qUHR1SQHOYkL0SPNpKzPZg.png" /></figure><ul><li>dist[u] represents the shortest known distance to node u</li><li>w(u,v) represents the weight of the edge from u to v</li><li>dist[v] represents the current shortest known distance to node v</li></ul><p>This continuous process of discovering and applying better paths is what gradually builds the final shortest path solution across the graph.</p><h4>3. Dijkstra Shortest Path Reconstruction</h4><p>In many practical scenarios, knowing only the shortest distance is not enough. We often need the actual sequence of nodes that forms the shortest path so we can understand how to travel from the source to the destination.</p><p>To support path reconstruction, Dijkstra’s algorithm can be extended with a parent array. Whenever relaxation discovers a better path to a node, the algorithm records which previous node led to that improvement. By storing these relationships during execution, we can later retrace the optimal route once the algorithm finishes.</p><p>The following implementation demonstrates how to reconstruct the full shortest path between two nodes while still using the standard priority queue–based version of Dijkstra’s algorithm.</p><pre>import java.util.*;<br><br>// Represents an edge in the graph<br>class Edge {<br><br>    // Destination node<br>    int to;<br><br>    // Weight (cost) of the edge<br>    int weight;<br><br>    // Constructor to create an edge<br>    Edge(int to, int weight) {<br>        this.to = to;<br>        this.weight = weight;<br>    }<br>}<br><br>public class Main {<br><br>    // Dijkstra&#39;s algorithm to find the shortest path<br>    public static List&lt;Integer&gt; shortestPath(<br>            List&lt;List&lt;Edge&gt;&gt; graph,<br>            int start,<br>            int target) {<br><br>        // Number of nodes in the graph<br>        int n = graph.size();<br><br>        // Stores shortest known distance from start node<br>        int[] dist = new int[n];<br><br>        // Stores previous node for path reconstruction<br>        int[] parent = new int[n];<br><br>        // Initialize all distances to infinity<br>        Arrays.fill(dist, Integer.MAX_VALUE);<br><br>        // Initialize parents as undefined<br>        Arrays.fill(parent, -1);<br><br>        // Distance to start node is 0<br>        dist[start] = 0;<br><br>        // Min-heap priority queue:<br>        // each element = {distance, node}<br>        PriorityQueue&lt;int[]&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(a -&gt; a[0]));<br><br>        // Start with the source node<br>        pq.offer(new int[]{0, start});<br><br>        // Process nodes until queue is empty<br>        while (!pq.isEmpty()) {<br><br>            // Get node with smallest distance<br>            int[] curr = pq.poll();<br><br>            int d = curr[0];<br>            int node = curr[1];<br><br>            // Skip outdated queue entries<br>            if (d &gt; dist[node]) continue;<br><br>            // Explore all neighbors of current node<br>            for (Edge edge : graph.get(node)) {<br><br>                int neighbor = edge.to;<br><br>                // Calculate new possible distance<br>                int newDist = dist[node] + edge.weight;<br><br>                // If a shorter path is found<br>                if (newDist &lt; dist[neighbor]) {<br><br>                    // Update shortest distance<br>                    dist[neighbor] = newDist;<br><br>                    // Remember best previous node<br>                    parent[neighbor] = node;<br><br>                    // Add updated distance to priority queue<br>                    pq.offer(new int[]{newDist, neighbor});<br>                }<br>            }<br>        }<br><br>        // Reconstruct shortest path<br>        List&lt;Integer&gt; path = new ArrayList&lt;&gt;();<br><br>        // Backtrack from target using parent array<br>        for (int at = target; at != -1; at = parent[at]) {<br>            path.add(at);<br>        }<br><br>        // Reverse because path was built backwards<br>        Collections.reverse(path);<br><br>        return path;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Number of nodes<br>        int n = 5;<br><br>        // Adjacency list representation of graph<br>        List&lt;List&lt;Edge&gt;&gt; graph = new ArrayList&lt;&gt;();<br><br>        // Initialize adjacency list for each node<br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        // Add directed weighted edges<br>        graph.get(0).add(new Edge(1, 4));<br>        graph.get(0).add(new Edge(2, 1));<br><br>        graph.get(2).add(new Edge(1, 2));<br>        graph.get(1).add(new Edge(3, 1));<br><br>        graph.get(3).add(new Edge(4, 3));<br><br>        // Find shortest path from node 0 to node 4<br>        List&lt;Integer&gt; path = shortestPath(graph, 0, 4);<br><br>        // Print resulting path<br>        System.out.println(&quot;Shortest path: &quot; + path);<br>    }<br>}<br><br>// Output:<br>// Shortest path: [0, 2, 1, 3, 4]</pre><p>After the shortest distances have been computed, the path is reconstructed by starting from the target node and repeatedly following the stored parent references backward until the source node is reached. Since this process builds the path in reverse order, the result is reversed at the end to produce the correct traversal sequence.</p><p>This extension is widely used in real-world systems because shortest distances alone rarely provide enough information. In most applications, the actual route taken through the graph is just as important as the final cost.</p><h4>3. Dijkstra Grid Implementation (Weighted Grid)</h4><p>Dijkstra’s algorithm is not limited to traditional graph structures. It can also be applied directly to grids where each cell has an associated movement cost. In this setting, every grid cell acts like a node, and moving between neighboring cells represents traversing weighted edges.</p><p>This approach is especially useful in environments where movement costs are not uniform. Instead of simply finding the path with the fewest moves, the algorithm searches for the path with the lowest total accumulated cost. As a result, a longer route may still be preferred if it is ultimately cheaper overall.</p><p>The following implementation demonstrates how Dijkstra’s algorithm can be adapted to a weighted 2D grid using a priority queue and distance tracking.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Dijkstra&#39;s algorithm on a 2D grid<br>    // Returns the minimum path cost from top-left to bottom-right<br>    public static int shortestPath(int[][] grid) {<br><br>        // Number of rows in the grid<br>        int rows = grid.length;<br><br>        // Number of columns in the grid<br>        int cols = grid[0].length;<br><br>        // dist[r][c] stores the minimum known cost to reach cell (r, c)<br>        int[][] dist = new int[rows][cols];<br><br>        // Initialize all distances to infinity<br>        for (int[] row : dist) {<br>            Arrays.fill(row, Integer.MAX_VALUE);<br>        }<br><br>        // Possible movement directions:<br>        // down, up, right, left<br>        int[][] dirs = {<br>                {1, 0},<br>                {-1, 0},<br>                {0, 1},<br>                {0, -1}<br>        };<br><br>        // Min-heap priority queue<br>        // each element = {cost, row, column}<br>        PriorityQueue&lt;int[]&gt; pq =<br>                new PriorityQueue&lt;&gt;(Comparator.comparingInt(a -&gt; a[0]));<br><br>        // Start at the top-left cell<br>        // Initial cost includes the value of the starting cell<br>        dist[0][0] = grid[0][0];<br><br>        // Add starting position to priority queue<br>        pq.offer(new int[]{grid[0][0], 0, 0});<br><br>        // Continue until all reachable cells are processed<br>        while (!pq.isEmpty()) {<br><br>            // Get cell with the smallest current cost<br>            int[] curr = pq.poll();<br><br>            int cost = curr[0];<br>            int r = curr[1];<br>            int c = curr[2];<br><br>            // Skip outdated entries in the priority queue<br>            if (cost &gt; dist[r][c]) continue;<br><br>            // If bottom-right cell is reached,<br>            // we found the minimum path cost<br>            if (r == rows - 1 &amp;&amp; c == cols - 1) {<br>                return cost;<br>            }<br><br>            // Explore all neighboring cells<br>            for (int[] d : dirs) {<br><br>                int nr = r + d[0];<br>                int nc = c + d[1];<br><br>                // Check if neighbor is inside grid boundaries<br>                if (nr &gt;= 0 &amp;&amp; nc &gt;= 0 &amp;&amp;<br>                    nr &lt; rows &amp;&amp; nc &lt; cols) {<br><br>                    // Calculate new cost to reach neighbor<br>                    int newCost = cost + grid[nr][nc];<br><br>                    // If a shorter path is found<br>                    if (newCost &lt; dist[nr][nc]) {<br><br>                        // Update shortest known cost<br>                        dist[nr][nc] = newCost;<br><br>                        // Add updated state to priority queue<br>                        pq.offer(new int[]{newCost, nr, nc});<br>                    }<br>                }<br>            }<br>        }<br><br>        // Return -1 if destination cannot be reached<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Example weighted grid<br>        int[][] grid = {<br>                {1, 3, 1},<br>                {1, 5, 1},<br>                {4, 2, 1}<br>        };<br><br>        // Compute shortest path cost<br>        int result = shortestPath(grid);<br><br>        // Print result<br>        System.out.println(&quot;Minimum path cost: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum path cost: 7</pre><p>The algorithm begins at the top-left corner and explores neighboring cells while continuously tracking the minimum known cost required to reach each position. Whenever a cheaper route to a cell is discovered, the distance is updated and the new state is added back into the priority queue for further exploration.</p><h4>4. Dijkstra Object-Based Graph Implementation</h4><p>In many real-world applications, graphs are not represented using simple integer indices or adjacency arrays. Instead, they are modeled through objects that directly reflect the structure of the problem domain. This makes the code more expressive, flexible, and easier to integrate into larger systems.</p><p>For example, an airline system can naturally be represented as a graph where airports act as nodes and flights act as weighted edges. Each flight contains an associated cost, allowing Dijkstra’s algorithm to calculate the cheapest route between airports.</p><p>The following implementation demonstrates how Dijkstra’s algorithm can operate on an object-oriented graph structure using custom Airport and Flight classes.</p><pre>import java.util.*;<br><br>class Airport {<br><br>    String name;<br><br>    List&lt;Flight&gt; flights = new ArrayList&lt;&gt;();<br><br>    Airport(String name) {<br>        this.name = name;<br>    }<br>}<br><br>class Flight {<br><br>    Airport destination;<br>    int cost;<br><br>    Flight(Airport destination, int cost) {<br>        this.destination = destination;<br>        this.cost = cost;<br>    }<br>}<br><br>public class Main {<br><br>    public static void dijkstra(Airport start) {<br><br>        Map&lt;Airport, Integer&gt; dist = new HashMap&lt;&gt;();<br><br>        PriorityQueue&lt;Map.Entry&lt;Airport, Integer&gt;&gt; pq =<br>                new PriorityQueue&lt;&gt;(<br>                        Comparator.comparingInt(Map.Entry::getValue)<br>                );<br><br>        dist.put(start, 0);<br><br>        pq.offer(Map.entry(start, 0));<br><br>        while (!pq.isEmpty()) {<br><br>            Map.Entry&lt;Airport, Integer&gt; current = pq.poll();<br><br>            Airport airport = current.getKey();<br>            int currentCost = current.getValue();<br><br>            // Skip outdated queue entries<br>            if (currentCost &gt; dist.get(airport)) {<br>                continue;<br>            }<br><br>            for (Flight flight : airport.flights) {<br><br>                Airport next = flight.destination;<br><br>                int newCost = currentCost + flight.cost;<br><br>                // Relaxation step<br>                if (!dist.containsKey(next) ||<br>                    newCost &lt; dist.get(next)) {<br><br>                    dist.put(next, newCost);<br><br>                    pq.offer(Map.entry(next, newCost));<br>                }<br>            }<br>        }<br><br>        // Print cheapest flight costs<br>        System.out.println(<br>                &quot;Cheapest flight costs from &quot; +<br>                start.name + &quot;:\n&quot;<br>        );<br><br>        for (Map.Entry&lt;Airport, Integer&gt; entry : dist.entrySet()) {<br><br>            Airport airport = entry.getKey();<br><br>            // Skip source airport<br>            if (airport == start) continue;<br><br>            System.out.println(<br>                    &quot;To &quot; + airport.name +<br>                    &quot; = $&quot; + entry.getValue()<br>            );<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        Airport london = new Airport(&quot;London&quot;);<br>        Airport paris = new Airport(&quot;Paris&quot;);<br>        Airport rome = new Airport(&quot;Rome&quot;);<br><br>        london.flights.add(new Flight(paris, 120));<br>        paris.flights.add(new Flight(rome, 90));<br><br>        // More expensive direct flight<br>        london.flights.add(new Flight(rome, 300));<br><br>        dijkstra(london);<br>    }<br>}<br><br>// Output:<br>// London -&gt; Paris = $120<br>// London -&gt; Rome = $210</pre><p>In this version, shortest distances are stored using a HashMap because nodes are represented by objects rather than numeric identifiers. The priority queue still performs the same essential role: always selecting the airport with the currently lowest known travel cost.</p><p>This object-based approach is common in production systems because it mirrors how many real-world domains are naturally modeled. Instead of separating graph data from application data, the graph structure becomes embedded directly within the domain objects themselves, resulting in designs that are often easier to maintain and extend.</p><h3>Practical Examples 💡</h3><p>Dijkstra’s algorithm is far more than a theoretical graph algorithm — it is a foundational technique used in many real-world systems that require efficient path optimization. Across very different domains, the underlying problem is often the same: determine the minimum accumulated cost through a weighted network.</p><p>Whether the “cost” represents distance, travel time, latency, energy consumption, or movement difficulty, Dijkstra’s algorithm systematically searches for the most efficient route between connected states.</p><h4>1. GPS Navigation Systems</h4><p>One of the most recognizable applications of Dijkstra’s algorithm is route planning and navigation. Road networks naturally form weighted graphs where intersections act as nodes and roads act as edges. Each edge is assigned a weight that may represent distance, estimated travel time, traffic conditions, or fuel consumption.</p><p>The goal is not simply to minimize the number of roads taken, but to minimize the total travel cost. As a result, a route containing more roads may still be faster if it uses high-speed highways or avoids congested areas.</p><p>The following example demonstrates a simplified navigation system that computes the shortest driving distance between cities.</p><pre>import java.util.*;<br><br>// Represents a road between cities<br>class Road {<br>    String destination;<br>    int distance;<br><br>    Road(String destination, int distance) {<br>        this.destination = destination;<br>        this.distance = distance;<br>    }<br>}<br><br>public class Main {<br><br>    // Dijkstra shortest path algorithm<br>    public static void dijkstra(<br>            Map&lt;String, List&lt;Road&gt;&gt; graph,<br>            String start) {<br><br>        // Stores shortest known distance to each city<br>        Map&lt;String, Integer&gt; dist = new HashMap&lt;&gt;();<br><br>        // Min-priority queue:<br>        // each entry = {distance, city}<br>        PriorityQueue&lt;Map.Entry&lt;String, Integer&gt;&gt; pq =<br>                new PriorityQueue&lt;&gt;(<br>                        Comparator.comparingInt(Map.Entry::getValue)<br>                );<br><br>        // Start city has distance 0<br>        dist.put(start, 0);<br><br>        pq.offer(Map.entry(start, 0));<br><br>        while (!pq.isEmpty()) {<br><br>            Map.Entry&lt;String, Integer&gt; current = pq.poll();<br><br>            String city = current.getKey();<br>            int currentDist = current.getValue();<br><br>            // Skip outdated queue entries<br>            if (currentDist &gt; dist.get(city)) {<br>                continue;<br>            }<br><br>            // Explore neighboring cities<br>            for (Road road : graph.getOrDefault(city, List.of())) {<br><br>                String nextCity = road.destination;<br><br>                // Compute candidate distance<br>                int newDist = currentDist + road.distance;<br><br>                // Relaxation step<br>                if (!dist.containsKey(nextCity) ||<br>                    newDist &lt; dist.get(nextCity)) {<br><br>                    dist.put(nextCity, newDist);<br><br>                    pq.offer(Map.entry(nextCity, newDist));<br>                }<br>            }<br>        }<br><br>        // Print shortest distances<br>        System.out.println(&quot;Shortest distances from &quot; + start + &quot;:&quot;);<br><br>        for (String city : dist.keySet()) {<br>            System.out.println(<br>                    city + &quot; = &quot; + dist.get(city)<br>            );<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Graph representation<br>        Map&lt;String, List&lt;Road&gt;&gt; graph = new HashMap&lt;&gt;();<br><br>        graph.put(&quot;Stockholm&quot;, List.of(<br>                new Road(&quot;Gothenburg&quot;, 5),<br>                new Road(&quot;Malmo&quot;, 15)<br>        ));<br><br>        graph.put(&quot;Gothenburg&quot;, List.of(<br>                new Road(&quot;Malmo&quot;, 3)<br>        ));<br><br>        graph.put(&quot;Malmo&quot;, List.of());<br><br>        // Run Dijkstra from Stockholm<br>        dijkstra(graph, &quot;Stockholm&quot;);<br>    }<br>}<br><br>// Output:<br>// Shortest distances from Stockholm:<br>// Malmo = 8<br>// Gothenburg = 5<br>// Stockholm = 0</pre><p>This example illustrates how navigation systems continuously evaluate possible routes and choose the path with the lowest total travel cost.</p><h4>2. Internet Routing</h4><p>Computer networks can also be represented as weighted graphs. In this context, routers act as nodes and network connections act as weighted edges. Different connections may carry different costs depending on latency, congestion, bandwidth, or reliability.</p><p>Routing systems use shortest-path algorithms to determine the most efficient path for transferring data across the network. This allows internet traffic to dynamically adapt to changing network conditions while still finding efficient communication routes.</p><p>The following example demonstrates a simplified router network where edge weights represent latency.</p><pre>import java.util.*;<br><br>// Represents a network connection<br>class Link {<br>    String target;<br>    int latency;<br><br>    Link(String target, int latency) {<br>        this.target = target;<br>        this.latency = latency;<br>    }<br>}<br><br>public class Main {<br><br>    public static void dijkstra(<br>            Map&lt;String, List&lt;Link&gt;&gt; network,<br>            String start) {<br><br>        // Stores minimum latency to each router<br>        Map&lt;String, Integer&gt; dist = new HashMap&lt;&gt;();<br><br>        // Priority queue ordered by latency<br>        PriorityQueue&lt;Map.Entry&lt;String, Integer&gt;&gt; pq =<br>                new PriorityQueue&lt;&gt;(<br>                        Comparator.comparingInt(Map.Entry::getValue)<br>                );<br><br>        dist.put(start, 0);<br><br>        pq.offer(Map.entry(start, 0));<br><br>        while (!pq.isEmpty()) {<br><br>            Map.Entry&lt;String, Integer&gt; current = pq.poll();<br><br>            String router = current.getKey();<br>            int currentLatency = current.getValue();<br><br>            // Ignore outdated queue states<br>            if (currentLatency &gt; dist.get(router)) {<br>                continue;<br>            }<br><br>            // Explore connected routers<br>            for (Link link : network.getOrDefault(router, List.of())) {<br><br>                int newLatency =<br>                        currentLatency + link.latency;<br><br>                // Relaxation step<br>                if (!dist.containsKey(link.target) ||<br>                    newLatency &lt; dist.get(link.target)) {<br><br>                    dist.put(link.target, newLatency);<br><br>                    pq.offer(<br>                            Map.entry(link.target, newLatency)<br>                    );<br>                }<br>            }<br>        }<br><br>        // Print minimum latencies<br>        System.out.println(&quot;Minimum network latencies:&quot;);<br><br>        for (String router : dist.keySet()) {<br>            System.out.println(<br>                    start + &quot; -&gt; &quot; +<br>                    router + &quot; = &quot; +<br>                    dist.get(router) + &quot; ms&quot;<br>            );<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        Map&lt;String, List&lt;Link&gt;&gt; network = new HashMap&lt;&gt;();<br><br>        network.put(&quot;A&quot;, List.of(<br>                new Link(&quot;B&quot;, 10),<br>                new Link(&quot;C&quot;, 3)<br>        ));<br><br>        network.put(&quot;B&quot;, List.of(<br>                new Link(&quot;D&quot;, 2)<br>        ));<br><br>        network.put(&quot;C&quot;, List.of(<br>                new Link(&quot;B&quot;, 1),<br>                new Link(&quot;D&quot;, 8)<br>        ));<br><br>        network.put(&quot;D&quot;, List.of());<br><br>        // Compute shortest network paths<br>        dijkstra(network, &quot;A&quot;);<br>    }<br>}<br><br>// Output:<br>// Minimum network latencies:<br>// A -&gt; A = 0 ms<br>// A -&gt; B = 4 ms<br>// A -&gt; C = 3 ms<br>// A -&gt; D = 6 ms</pre><p>This is conceptually similar to how real routing systems determine efficient communication paths across large-scale networks.</p><h4>3. Game Pathfinding</h4><p>Many games and simulations rely heavily on weighted pathfinding systems. Different terrain types often have different movement costs, meaning that some areas are slower or more expensive to traverse than others.</p><p>For example, moving across grass may be inexpensive, while mountains, water, or rough terrain may require significantly more movement cost. Dijkstra’s algorithm allows game systems to compute the cheapest overall route rather than merely the shortest geometric path.</p><p>The following example demonstrates pathfinding across a weighted terrain grid.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    public static int shortestPath(int[][] terrain) {<br><br>        int rows = terrain.length;<br>        int cols = terrain[0].length;<br><br>        // Stores minimum known cost to each cell<br>        int[][] dist = new int[rows][cols];<br><br>        for (int[] row : dist) {<br>            Arrays.fill(row, Integer.MAX_VALUE);<br>        }<br><br>        // Movement directions:<br>        // down, up, right, left<br>        int[][] dirs = {<br>                {1, 0},<br>                {-1, 0},<br>                {0, 1},<br>                {0, -1}<br>        };<br><br>        // Priority queue:<br>        // {cost, row, col}<br>        PriorityQueue&lt;int[]&gt; pq =<br>                new PriorityQueue&lt;&gt;(<br>                        Comparator.comparingInt(a -&gt; a[0])<br>                );<br><br>        // Starting position<br>        dist[0][0] = terrain[0][0];<br><br>        pq.offer(new int[]{terrain[0][0], 0, 0});<br><br>        while (!pq.isEmpty()) {<br><br>            int[] curr = pq.poll();<br><br>            int cost = curr[0];<br>            int r = curr[1];<br>            int c = curr[2];<br><br>            // Ignore outdated states<br>            if (cost &gt; dist[r][c]) {<br>                continue;<br>            }<br><br>            // Reached target cell<br>            if (r == rows - 1 &amp;&amp;<br>                c == cols - 1) {<br><br>                return cost;<br>            }<br><br>            // Explore neighboring cells<br>            for (int[] d : dirs) {<br><br>                int nr = r + d[0];<br>                int nc = c + d[1];<br><br>                // Boundary check<br>                if (nr &gt;= 0 &amp;&amp;<br>                    nc &gt;= 0 &amp;&amp;<br>                    nr &lt; rows &amp;&amp;<br>                    nc &lt; cols) {<br><br>                    // Compute new path cost<br>                    int newCost =<br>                            cost + terrain[nr][nc];<br><br>                    // Relaxation step<br>                    if (newCost &lt; dist[nr][nc]) {<br><br>                        dist[nr][nc] = newCost;<br><br>                        pq.offer(<br>                                new int[]{<br>                                        newCost,<br>                                        nr,<br>                                        nc<br>                                }<br>                        );<br>                    }<br>                }<br>            }<br>        }<br><br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Terrain movement costs<br>        int[][] terrain = {<br>                {1, 1, 5},<br>                {2, 8, 2},<br>                {1, 1, 1}<br>        };<br><br>        int result = shortestPath(terrain);<br><br>        System.out.println(<br>                &quot;Minimum movement cost: &quot; + result<br>        );<br>    }<br>}<br><br>// Output:<br>// Minimum movement cost: 6</pre><p>This style of weighted pathfinding is widely used in games, simulations, robotics, and AI systems where movement efficiency plays a critical role in decision-making.</p><h3>Conclusion 📣</h3><p>Dijkstra’s algorithm remains one of the most important and practical algorithms in computer science. By efficiently finding the minimum-cost path through weighted graphs, it provides the foundation for countless real-world systems ranging from navigation and networking to game AI and optimization software.</p><p>In this article, we explored how the algorithm works internally, examined the relaxation process that drives shortest-path updates, and implemented multiple Java solutions using graphs, grids, path reconstruction, and object-oriented models. Along the way, we also examined its time complexity, limitations, and common real-world applications.</p><p>Although more specialized algorithms exist for certain scenarios, Dijkstra’s algorithm continues to be a fundamental tool because of its simplicity, correctness, and versatility. Understanding how it works not only strengthens your knowledge of graph theory, but also builds a foundation for learning more advanced pathfinding and optimization algorithms such as A*, Bellman–Ford, Floyd–Warshall, and many others.</p><p>If you want to deepen your understanding further, a great next step is experimenting with variations of the algorithm yourself — such as reconstructing full routes, optimizing large graphs, or adapting Dijkstra’s algorithm to new problem domains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7af310e466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Depth-First Search (DFS) in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/depth-first-search-dfs-in-java-learn-with-practical-examples-d02ec9719622?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/d02ec9719622</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Fri, 15 May 2026 07:34:16 GMT</pubDate>
            <atom:updated>2026-05-15T07:34:16.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJ0L6bx4gTJiZRkwCnE5fw.png" /></figure><p>Depth-First Search (DFS) is one of the most important traversal algorithms in computer science. It is commonly used with graphs and trees, but its applications extend far beyond those structures. Any problem that can be modeled as connected states or nodes can potentially be explored using DFS.</p><p>DFS works by exploring one path as deeply as possible before backtracking and trying alternative paths. This “go deep first” behavior makes DFS especially useful for problems involving exhaustive exploration, recursion, backtracking, path generation, and structural analysis.</p><p>The roots of DFS trace back to early graph theory and combinatorial research in the 19th and 20th centuries. As computer science evolved, DFS became foundational in areas such as compiler design, maze solving, dependency analysis, and artificial intelligence.</p><p>Today, DFS powers many important algorithms and systems, including cycle detection, topological sorting, connected component analysis, puzzle solving, recursive search problems, and state-space exploration.</p><p>In this article, we’ll explore how DFS works, implement it in Java, and examine where it shines — and where it falls short.</p><h3>What Is Depth-First Search? 🔍</h3><p>Depth-First Search (DFS) is an algorithm for traversing or exploring connected nodes or states by continuously moving deeper into a structure before backtracking and exploring alternative paths. Here is the core idea:</p><ul><li>Start at a source node</li><li>Visit one of its neighboring nodes</li><li>Then visit a neighbor of that node</li><li>Continue moving deeper as long as unvisited nodes remain</li><li>When no further progress is possible, backtrack to the previous node</li><li>Repeat the process until all reachable nodes have been explored</li></ul><p>This “deep exploration first” behavior is what gives DFS its name. Rather than exploring nearby nodes evenly, DFS commits to a single path and follows it as far as possible before returning to earlier branching points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*C4PNW6JKPrxGhNveGCOipA.gif" /><figcaption>Animation of Depth-First Search. <a href="https://commons.wikimedia.org/wiki/File:Depth-First-Search.gif">Mre</a>, <a href="https://creativecommons.org/licenses/by-sa/3.0">CC BY-SA 3.0</a>, via Wikimedia Commons</figcaption></figure><p>To implement this efficiently, DFS typically relies on recursion, which is the most common and intuitive approach, or an explicit stack in iterative implementations.</p><p>In graph problems, DFS also usually requires a visited set (or visited array) to prevent revisiting the same nodes repeatedly, which could otherwise lead to infinite loops in cyclic graphs.</p><p>A useful way to visualize DFS is to imagine exploring a maze. Instead of checking every nearby corridor first, you pick one path and keep walking until you hit a dead end. Only then do you backtrack to the last intersection and try a different route.</p><h3>When Should You Use DFS? 🧐</h3><p>DFS is a traversal strategy built for deep, path-driven exploration. It proceeds by following a single branch as far as it can go before backtracking to try other possibilities. Because of this behavior, it is particularly well-suited for problems that involve exploring structured spaces, generating paths, or navigating complex decision trees.</p><p>Common use cases include:</p><ul><li><strong>Maze / puzzle solving:</strong> DFS explores one path at a time until it hits a dead end or finds the goal, then backtracks to try other routes. This matches how many puzzles are naturally solved through trial and error.</li><li><strong>Graph analysis:</strong> It helps detect cycles, find connected components, and identify strongly connected components by deeply traversing reachable nodes and tracking visited paths or recursion states.</li><li><strong>Trees:</strong> DFS is ideal for hierarchical structures, allowing full traversal of a branch before moving to the next. It supports pre-order, in-order, and post-order traversal patterns.</li><li><strong>Topological sorting:</strong> DFS processes dependencies first, then records nodes in finishing order to produce a valid task sequence for directed acyclic graphs.</li><li><strong>Backtracking problems:</strong> In problems like Sudoku, N-Queens, or permutations, DFS builds solutions step by step and backtracks whenever a constraint is violated.</li><li><strong>State-space search:</strong> DFS explores sequences of decisions or moves in games or planning problems, diving deep into one possibility before trying alternatives.</li></ul><p>From a performance perspective, DFS runs in O(V + E) time and uses O(V) space, where <em>V</em> represents the number of vertices (nodes) and <em>E</em> represents the number of edges.</p><p>In practice, DFS is often more memory-efficient than Breadth-First Search (BFS) because it only keeps track of the current path (plus recursion or stack overhead), rather than storing all nodes at the current depth level.</p><h3>Limitations of DFS 📉</h3><p>Although DFS is a powerful and widely used traversal strategy, it comes with several important limitations that can affect its suitability depending on the problem.</p><ul><li><strong>Does not guarantee the shortest path:</strong> DFS explores one branch deeply before considering alternatives, which means it may find a valid solution quickly but not the optimal one. In unweighted graphs, it can return a much longer path even when a shorter route exists.</li><li><strong>Can explore deep or unproductive paths for too long:</strong> In graphs with very deep branches — or in extreme cases, effectively infinite paths — DFS may spend significant time going down a path that does not lead to a solution before it backtracks. This can make it inefficient in large or poorly structured search spaces.</li><li><strong>Risk of stack overflow with recursion:</strong> Recursive DFS relies on the system call stack, which has limited depth. In very deep trees or graphs, this can lead to a stack overflow error (e.g., in Java or Python). Iterative DFS using an explicit stack can help avoid this issue.</li><li><strong>Requires careful handling of cycles:</strong> In graphs that contain cycles, DFS must track visited nodes properly. Without a visited set, it may revisit the same nodes repeatedly, potentially leading to infinite loops or redundant computation.</li></ul><p>Overall, DFS is an elegant and versatile algorithm that excels in recursive and exhaustive exploration problems. However, its effectiveness depends on the structure of the problem, and it must be chosen carefully when optimality, depth control, or safety from infinite exploration are important.</p><h3>From Theory to Practice 🛠️</h3><p>DFS is a general-purpose exploration strategy that is not tied to any specific data structure. It can be applied anywhere we can define a starting state and a way to move to neighboring states.</p><p>Whether the problem is represented as a graph, tree, grid, or even an abstract state space, DFS always follows the same core idea: it explores by going deep first, then backtracking to try alternative paths when needed.</p><p>With this pattern in mind, we can now move from the underlying concept to concrete, real-world examples.</p><h4>1. DFS Graph Implementation (Recursive)</h4><p>Let’s begin with a standard recursive DFS implementation using an adjacency list representation of a graph. This example highlights the fundamental structure of DFS: marking a node as visited, processing it, and then recursively exploring its neighbors before backtracking.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Recursive DFS traversal<br>    public static void dfs(List&lt;List&lt;Integer&gt;&gt; graph, int node, boolean[] visited) {<br><br>        // Mark the current node as visited<br>        visited[node] = true;<br><br>        // Process the current node<br>        System.out.print(node + &quot; &quot;);<br><br>        // Explore all neighboring nodes<br>        for (int neighbor : graph.get(node)) {<br><br>            // Continue only if the neighbor has not been visited<br>            if (!visited[neighbor]) {<br><br>                // Recurse deeper into the graph<br>                dfs(graph, neighbor, visited);<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        int n = 5;<br><br>        // Build adjacency list representation<br>        List&lt;List&lt;Integer&gt;&gt; graph = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        /*<br>              0<br>             / \<br>            1   2<br>            |   |<br>            3   4<br>        */<br><br>        // Undirected edges<br>        graph.get(0).add(1);<br>        graph.get(1).add(0);<br><br>        graph.get(0).add(2);<br>        graph.get(2).add(0);<br><br>        graph.get(1).add(3);<br>        graph.get(3).add(1);<br><br>        graph.get(2).add(4);<br>        graph.get(4).add(2);<br><br>        boolean[] visited = new boolean[n];<br><br>        System.out.print(&quot;DFS Traversal: &quot;);<br>        dfs(graph, 0, visited);<br>    }<br>}<br><br>// Output:<br>// DFS Traversal: 0 1 3 2 4</pre><p>This example follows the characteristic DFS pattern: it dives into one branch as far as possible before returning to explore other options.</p><p>A simplified view of the traversal looks like this:</p><pre>0<br>└── 1<br>    └── 3<br>(backtrack)<br>└── 2<br>    └── 4</pre><p>The key idea is that DFS prioritizes depth over breadth. Instead of exploring all neighbors evenly at each step like BFS, it fully commits to a path before backtracking and continuing with the next available branch.</p><h4>2. DFS Graph Implementation (Iterative)</h4><p>DFS can also be implemented iteratively using an explicit stack. This approach removes recursion and gives you more control over the traversal process, while still preserving the same depth-first behavior.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Iterative DFS traversal using a stack<br>    public static void dfsIterative(List&lt;List&lt;Integer&gt;&gt; graph, int start) {<br><br>        boolean[] visited = new boolean[graph.size()];<br>        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();<br><br>        // Start from the initial node<br>        stack.push(start);<br><br>        while (!stack.isEmpty()) {<br><br>            int node = stack.pop();<br><br>            // Skip if already visited<br>            if (visited[node]) continue;<br><br>            visited[node] = true;<br><br>            // Process current node<br>            System.out.print(node + &quot; &quot;);<br><br>            // Add neighbors to stack<br>            // (reverse order is sometimes used to match recursive output)<br>            for (int neighbor : graph.get(node)) {<br>                if (!visited[neighbor]) {<br>                    stack.push(neighbor);<br>                }<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        int n = 5;<br><br>        List&lt;List&lt;Integer&gt;&gt; graph = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        /*<br>              0<br>             / \<br>            1   2<br>            |   |<br>            3   4<br>        */<br><br>        graph.get(0).add(1);<br>        graph.get(1).add(0);<br><br>        graph.get(0).add(2);<br>        graph.get(2).add(0);<br><br>        graph.get(1).add(3);<br>        graph.get(3).add(1);<br><br>        graph.get(2).add(4);<br>        graph.get(4).add(2);<br><br>        System.out.print(&quot;DFS Iterative Traversal: &quot;);<br>        dfsIterative(graph, 0);<br>    }<br>}<br><br>// Output (may vary slightly depending on stack order):<br>// DFS Iterative Traversal: 0 2 4 1 3</pre><p>The iterative version works the same way as recursion, but instead of relying on the call stack, it uses an explicit stack data structure. This makes the traversal order and memory usage more transparent, and avoids recursion depth limits in very large graphs.</p><p>At its core, it still follows the same DFS principle: go deep first, then backtrack and explore alternatives.</p><h4>3. DFS Tree Implementation</h4><p>A tree is a specialized form of graph with two defining properties: it contains no cycles, and it has a clear hierarchical structure in which each node (except the root) has exactly one parent and zero or more children.</p><p>Because of this recursive, branching structure, trees are one of the most natural applications for DFS. The recursive nature of DFS aligns directly with the structure of a tree, making traversal intuitive: each node can be processed in the same way as its children, allowing the algorithm to seamlessly move deeper into subtrees before backtracking.</p><pre>class TreeNode {<br>    String val;<br>    TreeNode left, right;<br><br>    TreeNode(String val) {<br>        this.val = val;<br>    }<br>}<br><br>public class Main {<br><br>    // Preorder DFS traversal<br>    public static void dfsTree(TreeNode node) {<br><br>        // Base case<br>        if (node == null) return;<br><br>        // Process current node<br>        System.out.print(node.val + &quot; &quot;);<br><br>        // Recursively explore left subtree<br>        dfsTree(node.left);<br><br>        // Recursively explore right subtree<br>        dfsTree(node.right);<br>    }<br><br>    public static void main(String[] args) {<br><br>        /*<br>                 A<br>               /   \<br>              B     C<br>             / \     \<br>            D   E     F<br>        */<br><br>        TreeNode root = new TreeNode(&quot;A&quot;);<br><br>        root.left = new TreeNode(&quot;B&quot;);<br>        root.right = new TreeNode(&quot;C&quot;);<br><br>        root.left.left = new TreeNode(&quot;D&quot;);<br>        root.left.right = new TreeNode(&quot;E&quot;);<br><br>        root.right.right = new TreeNode(&quot;F&quot;);<br><br>        System.out.print(&quot;DFS Preorder Traversal: &quot;);<br><br>        dfsTree(root);<br>    }<br>}<br><br>// Output:<br>// DFS Preorder Traversal: A B D E C F</pre><p>DFS naturally mirrors the hierarchical structure of a tree by exploring each branch fully before returning to earlier nodes through backtracking. This results in a traversal pattern that moves downward through the tree’s depth first, making it especially intuitive for recursive tree processing and operations that depend on visiting a node before or after its children.</p><h4>4. DFS Path Search Implementation</h4><p>DFS is often used when the goal is not to explore everything, but simply to determine whether a path exists between two nodes. It focuses on exploration rather than optimization, meaning it may find a valid route quickly by diving deep into the graph, even though it does not guarantee the shortest path.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Returns true if the target node is reachable from the current node<br>    public static boolean hasPath(<br>            List&lt;List&lt;Integer&gt;&gt; graph,<br>            int current,<br>            int target,<br>            boolean[] visited) {<br><br>        // Base case: target found<br>        if (current == target) {<br>            return true;<br>        }<br><br>        visited[current] = true;<br><br>        // Explore all neighbors<br>        for (int neighbor : graph.get(current)) {<br><br>            if (!visited[neighbor]) {<br><br>                // Stop immediately if a valid path is found<br>                if (hasPath(graph, neighbor, target, visited)) {<br>                    return true;<br>                }<br>            }<br>        }<br><br>        return false;<br>    }<br><br>    public static void main(String[] args) {<br><br>        int n = 5;<br><br>        List&lt;List&lt;Integer&gt;&gt; graph = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        // Build graph<br>        graph.get(0).add(1);<br>        graph.get(1).add(0);<br><br>        graph.get(1).add(2);<br>        graph.get(2).add(1);<br><br>        graph.get(2).add(3);<br>        graph.get(3).add(2);<br><br>        boolean[] visited = new boolean[n];<br><br>        boolean result = hasPath(graph, 0, 3, visited);<br><br>        System.out.println(&quot;Path exists: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Path exists: true</pre><p>This approach works efficiently for reachability queries because DFS can terminate early as soon as the target is discovered. Unlike shortest-path algorithms, it does not continue exploring once a valid route is found, making it well-suited for simple existence checks rather than optimal path finding.</p><h4>5. DFS Grid Implementation (Maze Exploration)</h4><p>Grids can be naturally modeled as graphs, where each cell represents a node and valid movements between adjacent cells represent edges. From this perspective, DFS becomes a powerful tool for exploring grids, especially in problems like maze traversal, island counting, and flood-fill operations.</p><pre>public class Main {<br><br>    static int rows, cols;<br><br>    // DFS exploration in a grid<br>    public static void dfsGrid(<br>            int[][] grid,<br>            int r,<br>            int c,<br>            boolean[][] visited) {<br><br>        // Boundary checks and invalid conditions<br>        if (r &lt; 0 || c &lt; 0 ||<br>            r &gt;= rows || c &gt;= cols ||<br>            grid[r][c] == 1 ||<br>            visited[r][c]) {<br><br>            return;<br>        }<br><br>        // Mark current cell as visited<br>        visited[r][c] = true;<br><br>        System.out.println(&quot;Visited: (&quot; + r + &quot;, &quot; + c + &quot;)&quot;);<br><br>        // Explore all four directions<br>        dfsGrid(grid, r + 1, c, visited);<br>        dfsGrid(grid, r - 1, c, visited);<br>        dfsGrid(grid, r, c + 1, visited);<br>        dfsGrid(grid, r, c - 1, visited);<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[][] grid = {<br>                {0, 0, 1, 0},<br>                {1, 0, 1, 0},<br>                {0, 0, 0, 0},<br>                {0, 1, 1, 0}<br>        };<br><br>        rows = grid.length;<br>        cols = grid[0].length;<br><br>        boolean[][] visited = new boolean[rows][cols];<br><br>        dfsGrid(grid, 0, 0, visited);<br>    }<br>}<br><br>// Output:<br>// Visited: (0, 0)<br>// Visited: (0, 1)<br>// Visited: (1, 1)<br>// Visited: (2, 1)<br>// Visited: (2, 2)<br>// Visited: (2, 3)<br>// Visited: (3, 3)<br>// Visited: (1, 3)<br>// Visited: (0, 3)<br>// Visited: (2, 0)<br>// Visited: (3, 0)</pre><p>In this setup, DFS treats the grid like a maze and explores one direction as far as possible before backtracking to try alternative paths. This depth-first behavior makes it especially effective for recursive exploration tasks such as discovering connected regions or simulating flood-fill algorithms, where each reachable cell must be fully explored before moving on.</p><h4>6. DFS State Space Implementation (Backtracking)</h4><p>DFS is the core technique behind backtracking algorithms. Instead of simply traversing an existing structure, it explores an entire decision space by building solutions step by step and abandoning paths that cannot lead to valid results.</p><p>A classic example is generating all permutations of a set of numbers, where each decision point represents choosing the next element in the sequence.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Generates all permutations using DFS + backtracking<br>    public static void permute(<br>            List&lt;Integer&gt; path,<br>            boolean[] used,<br>            int[] nums) {<br><br>        // Base case: a complete permutation has been formed<br>        if (path.size() == nums.length) {<br>            System.out.println(path);<br>            return;<br>        }<br><br>        // Try each unused number as the next choice<br>        for (int i = 0; i &lt; nums.length; i++) {<br><br>            if (used[i]) continue;<br><br>            // Choose<br>            used[i] = true;<br>            path.add(nums[i]);<br><br>            // Explore deeper with this choice<br>            permute(path, used, nums);<br><br>            // Backtrack (undo the choice)<br>            path.remove(path.size() - 1);<br>            used[i] = false;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[] nums = {1, 2, 3};<br><br>        permute(new ArrayList&lt;&gt;(), new boolean[nums.length], nums);<br>    }<br>}<br><br>// Output:<br>// [1, 2, 3]<br>// [1, 3, 2]<br>// [2, 1, 3]<br>// [2, 3, 1]<br>// [3, 1, 2]<br>// [3, 2, 1]</pre><p>This pattern — choose → explore → unchoose (backtrack) — is the defining structure of DFS in combinatorial problems. It appears across a wide range of tasks such as generating combinations, solving constraint puzzles, and exploring all possible configurations in a search space.</p><h4>7. DFS Object-Based Graph Implementation</h4><p>In real-world applications, graphs are often not stored as adjacency lists or matrices, but as interconnected objects with explicit relationships. A social network is a natural example of this model, where each user directly references their connections.</p><pre>import java.util.*;<br><br>class User {<br><br>    String name;<br><br>    List&lt;User&gt; friends = new ArrayList&lt;&gt;();<br><br>    User(String name) {<br>        this.name = name;<br>    }<br>}<br><br>public class Main {<br><br>    // DFS traversal of a social graph<br>    public static void dfs(User user, Set&lt;User&gt; visited) {<br><br>        visited.add(user);<br><br>        System.out.println(&quot;Visiting: &quot; + user.name);<br><br>        // Traverse all direct connections<br>        for (User friend : user.friends) {<br><br>            if (!visited.contains(friend)) {<br><br>                dfs(friend, visited);<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        User alice = new User(&quot;Alice&quot;);<br>        User bob = new User(&quot;Bob&quot;);<br>        User carol = new User(&quot;Carol&quot;);<br>        User dave = new User(&quot;Dave&quot;);<br><br>        alice.friends.add(bob);<br>        bob.friends.add(carol);<br>        carol.friends.add(dave);<br><br>        dfs(alice, new HashSet&lt;&gt;());<br>    }<br>}<br><br>// Output:<br>// Visiting: Alice<br>// Visiting: Bob<br>// Visiting: Carol<br>// Visiting: Dave</pre><p>In this representation, DFS operates directly on object relationships rather than indices or arrays. Each object acts as a node, and its references define the edges of the graph. The traversal naturally follows these links, diving deep through connected relationships before backtracking to explore alternative paths.</p><h3>Practical Examples 💡</h3><p>DFS shows up frequently in real-world systems wherever data is naturally hierarchical or requires exhaustive exploration of nested structures. Its recursive nature makes it a natural fit for problems that mirror tree-like or graph-like relationships.</p><h4>1. File System Traversal</h4><p>Operating systems and tools that index or search files often rely on DFS-style traversal to walk through directory structures. A filesystem is inherently hierarchical, making it a direct match for recursive exploration.</p><pre>import java.io.File;<br><br>public class Main {<br><br>    // Recursively explores folders using DFS<br>    public static void traverse(File file) {<br><br>        // Process current file or directory<br>        System.out.println(file.getName());<br><br>        // If this is a directory, explore its contents<br>        if (file.isDirectory()) {<br><br>            File[] children = file.listFiles();<br><br>            if (children != null) {<br><br>                for (File child : children) {<br>                    traverse(child);<br>                }<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        File root = new File(&quot;C:\\Users\\MyUser\\Documents\\MyFolder&quot;);<br><br>        traverse(root);<br>    }<br>}</pre><p>Because each directory can contain subdirectories, and those can contain even more nested structures, DFS naturally follows this hierarchy by fully exploring one branch before moving to the next.</p><h4>2. Comment Thread Traversal (Reddit / YouTube / Forums)</h4><p>Platforms like Reddit, YouTube, or news sites often store comments in a nested structure, where a comment can have replies, and those replies can have replies again. This forms a tree-like structure.</p><p>DFS is can be used to display comment threads, compute total replies under a comment, and search for a specific comment in a thread:</p><pre>import java.util.*;<br><br>class Comment {<br><br>    String text;<br>    List&lt;Comment&gt; replies = new ArrayList&lt;&gt;();<br><br>    Comment(String text) {<br>        this.text = text;<br>    }<br>}<br><br>public class Main {<br><br>    // DFS traversal of comment tree<br>    public static void printThread(Comment comment, int depth) {<br><br>        // Indentation shows hierarchy<br>        for (int i = 0; i &lt; depth; i++) {<br>            System.out.print(&quot;  &quot;);<br>        }<br><br>        System.out.println(comment.text);<br><br>        // Explore replies deeply<br>        for (Comment reply : comment.replies) {<br>            printThread(reply, depth + 1);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        Comment root = new Comment(&quot;Great post!&quot;);<br><br>        Comment r1 = new Comment(&quot;Thanks!&quot;);<br>        Comment r2 = new Comment(&quot;I agree!&quot;);<br>        Comment r3 = new Comment(&quot;Can you explain more?&quot;);<br>        Comment r4 = new Comment(&quot;Sure, here it is.&quot;);<br><br>        root.replies.add(r1);<br>        root.replies.add(r2);<br>        r2.replies.add(r3);<br>        r3.replies.add(r4);<br><br>        printThread(root, 0);<br>    }<br>}<br><br>// Output:<br>// Great post!<br>//   Thanks!<br>//   I agree!<br>//     Can you explain more?<br>//       Sure, here it is.</pre><p>DFS is ideal here comment systems are naturally hierarchical. Each comment can spawn an entire subtree of discussions. DFS fits perfectly because it fully explores one conversation branch before moving to another, preserves natural nesting structure, and mirrors how humans read discussions (top → reply → reply-of-reply)</p><h4>3. Solving Mazes and Puzzles</h4><p>DFS is widely used in puzzle-solving systems because it explores possible moves deeply before backtracking when a path fails. This makes it a natural fit for problems where the solution is not known in advance and must be discovered through systematic trial and error.</p><p>Typical examples include:</p><ul><li>Sudoku solvers</li><li>N-Queens problem</li><li>Crossword or word search puzzles</li><li>Game AI decision-making</li><li>General constraint satisfaction problems</li></ul><p>In all of these cases, the problem can be modeled as a decision tree, where each move leads to a new state. DFS then explores this state space one branch at a time, backtracking whenever a choice leads to an invalid or dead-end configuration.</p><p><strong>Example: Simple Maze Solver (DFS)</strong></p><pre>public class Main {<br>    static int rows, cols;<br>    <br>    // Movement directions: down, up, right, left<br>    static int[][] directions = {<br>            {1, 0}, {-1, 0}, {0, 1}, {0, -1}<br>    };<br><br>    // DFS-based maze solver (checks if destination is reachable)<br>    public static boolean solveMaze(<br>            int[][] maze,<br>            int r,<br>            int c,<br>            int destR,<br>            int destC,<br>            boolean[][] visited) {<br>        // Boundary + validity checks<br>        if (r &lt; 0 || c &lt; 0 ||<br>            r &gt;= rows || c &gt;= cols ||<br>            maze[r][c] == 1 || visited[r][c]) {<br>            return false;<br>        }<br>        // Base case: destination reached<br>        if (r == destR &amp;&amp; c == destC) {<br>            return true;<br>        }<br>        // Mark current cell as visited<br>        visited[r][c] = true;<br>        // Explore all four directions<br>        for (int[] dir : directions) {<br>            int newR = r + dir[0];<br>            int newC = c + dir[1];<br>            // If any path leads to destination, stop early<br>            if (solveMaze(maze, newR, newC, destR, destC, visited)) {<br>                return true;<br>            }<br>        }<br>        // Backtrack<br>        return false;<br>    }<br>    public static void main(String[] args) {<br>        int[][] maze = {<br>                {0, 0, 1, 0},<br>                {1, 0, 1, 0},<br>                {0, 0, 0, 0},<br>                {0, 1, 1, 0}<br>        };<br>        rows = maze.length;<br>        cols = maze[0].length;<br>        boolean[][] visited = new boolean[rows][cols];<br>        int startR = 0, startC = 0;<br>        int destR = 3, destC = 3;<br>        boolean found = solveMaze(maze, startR, startC, destR, destC, visited);<br>        System.out.println(&quot;Path exists: &quot; + found);<br>    }<br>}<br><br>// Output:<br>// Path exists: true</pre><p>The key idea is that each cell (or move) represents a decision point. DFS explores one sequence of decisions as far as possible, and when it fails, it backtracks and tries another. This makes it especially powerful for problems where the solution space is large but structured.</p><h3>Conclusion 📣</h3><p>Depth-First Search is one of the most elegant and widely applicable algorithms in computer science. While Breadth-First Search expands outward level by level, DFS takes the opposite approach: it commits to a single path and explores it as deeply as possible before backtracking to consider alternative routes.</p><p>Across graphs, trees, grids, recursive structures, and abstract state spaces, the same fundamental pattern keeps appearing: a node or state is visited, its possibilities are explored recursively or via a stack, and when no further progress can be made, the algorithm backtracks and continues from the last decision point.</p><p>This simple yet powerful mechanism is what makes DFS so effective. It naturally aligns with problems that involve hierarchical structure, recursive decomposition, and exhaustive exploration of possibilities.</p><p>DFS is especially useful in problems involving recursive traversal, backtracking, path construction, connectivity analysis, cycle detection, and general state-space exploration.</p><p>However, it is not always the optimal choice. DFS does not guarantee the shortest path, it can become inefficient when it goes deep into unproductive branches, and recursive implementations may run into stack limitations in very large problem spaces.</p><p>Despite these limitations, DFS remains a core foundational algorithm. Understanding it is not just about learning how to traverse data structures — it is about developing a mindset for structured exploration, where you go deep into possibilities, fully investigate them, and intelligently backtrack when needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d02ec9719622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breadth-First Search (BFS) in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/breadth-first-search-bfs-in-java-learn-with-practical-examples-9801a76ba137?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/9801a76ba137</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Thu, 14 May 2026 08:49:18 GMT</pubDate>
            <atom:updated>2026-05-14T08:49:18.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gE1L6dkju8UgIbCtylvH2A.png" /></figure><p>Breadth-First Search (BFS) is one of the most fundamental traversal algorithms in computer science. It is commonly used with graphs and trees, but it can solve any problem that can be modeled as connected nodes or states.</p><p>BFS explores nodes step by step, visiting all neighboring nodes at the current level before moving to the next level. Because of this level-by-level traversal, it is especially useful for finding the shortest path in unweighted graphs and similar structures. This differs from depth-first approaches, which continue exploring one path as far as possible before backtracking.</p><p>The concept of BFS dates back to early graph theory research in the mid-20th century and became more important as computer systems began modeling real-world relationships such as networks, maps, and social connections, where exploring data layer by layer is often the most practical approach.</p><p>Today, BFS is a core building block in areas like networking, pathfinding, recommendation systems, and artificial intelligence, and it frequently appears in problems involving trees, grids, and implicit state spaces.</p><p>In this article, we’ll explore how BFS works, implement it in Java, and examine where it shines — and where it falls short.</p><h3>What Is Breadth-First Search? 🔍</h3><p>BFS is an algorithm for traversing or exploring connected nodes or states by starting from a source node and visiting all neighboring nodes before moving to the next level. Here’s the core idea:</p><ul><li>Start at a source node</li><li>Visit all its immediate neighbors</li><li>Then visit neighbors of those neighbors</li><li>Continue level by level until all reachable nodes are explored (or target is found)</li></ul><p>To do this efficiently, the algorithm uses a queue to keep track of what to visit next, and typically a visited set to avoid processing the same node multiple times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*on5z7UjsKdnc7Ujn4aqRHQ.gif" /><figcaption>Animation of BFS. <a href="https://commons.wikimedia.org/wiki/File:Animated_BFS.gif">Blake Matheny</a>, <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0</a>, via Wikimedia Commons</figcaption></figure><p>You can think of BFS like ripples in water — when you drop a stone, the waves expand outward evenly in all directions.</p><h3>When Should You Use BFS? 🧐</h3><p>BFS is a good choice when you need to explore a problem level by level or find the shortest path in a system where each step has equal cost. Because it visits nodes in order of increasing distance, it guarantees the shortest path in terms of number of steps. This makes BFS especially useful in problems like:</p><ul><li><strong>Grids / mazes:</strong> finding the minimum number of moves from a start cell to a target (e.g., shortest path in a maze or a game board).</li><li><strong>Unweighted graphs:</strong> computing the shortest path between two nodes in a network where all edges have the same cost.</li><li><strong>Networks / relationship graphs:</strong> finding the minimum number of connections between two nodes (e.g., degrees of separation)</li><li><strong>Trees:</strong> performing level-order traversal or finding all nodes at distance <em>k</em> from a root.</li><li><strong>Multi-source problems:</strong> starting from multiple points at once, such as finding the nearest hospital, exit, or “0” in a matrix.</li></ul><p>In terms of performance, BFS runs in O(V + E) time and uses O(V) space, where <em>V</em> is the number of nodes and <em>E</em> is the number of edges. This makes it efficient for many traversal and shortest-path problems, especially when the graph is not too large or deep.</p><p>That said, BFS can become memory-intensive when the search space is very wide. For example, in a grid where each position can branch into many new positions, BFS must store all positions at the current distance before moving forward. If one level contains thousands or millions of nodes, memory usage can grow quickly.</p><h3>Limitations of BFS 📉</h3><p>While BFS is powerful, it might not always be the right tool — especially when its guarantees are unnecessary or too costly.</p><ul><li><strong>High memory usage:</strong> A key limitation of BFS is memory consumption. In problems with a high branching factor, the number of nodes grows rapidly at each level. For example, in a game tree where each state has 10 possible moves, BFS may need to store up to 10^<em>d</em> nodes at depth <em>d</em>. Even at depth 6, this can reach around 1 million nodes, which quickly becomes impractical.</li><li><strong>Inefficient when shortest path is not needed:</strong> BFS is designed to find the shortest path in unweighted graphs. However, if any valid solution is acceptable, it may spend significant time exploring all shallow levels first. In such cases, DFS can often reach a solution faster by going deeper immediately.</li><li><strong>Not suitable for weighted graphs:</strong> BFS assumes all edges have equal cost. When edge weights vary (for example, roads with different travel times), BFS may return a path with fewer steps but a higher total cost. For these cases, algorithms like Dijkstra’s algorithm are required to correctly compute the shortest path.</li><li><strong>Poor scalability in large and dense graphs:</strong> In very large state spaces or dense graphs, BFS can quickly become impractical due to its memory requirements. Exploring all possible configurations (such as in complex puzzles) can exhaust available memory. In such scenarios, more space-efficient approaches like DFS or informed search strategies like A* are often better suited.</li></ul><p>Overall, BFS is a simple and powerful algorithm that guarantees correct results in many unweighted search problems. However, its performance depends heavily on the size and structure of the problem. Understanding when to use BFS — and when to choose a more specialized algorithm — is key to writing efficient solutions in real-world applications and coding interviews.</p><h3>From Theory to Practice 🛠️</h3><p>BFS is often introduced using graphs, but the idea behind it is more general. It is not tied to any specific data structure — what matters is having a starting point and a way to discover neighboring states. Once those two conditions are met, BFS can be applied to trees, graphs, grids, or even abstract problem spaces.</p><p>At its core, every BFS implementation follows the same pattern: a queue is used to control the order of exploration, nodes are processed level by level, and a visited set is used when needed to avoid revisiting the same state.</p><p>With this foundation in place, let’s look at some practical examples.</p><h4>1. BFS Graph Implementation</h4><p>Let’s begin with a standard BFS implementation using an adjacency list representation of a graph. This example highlights the core mechanics of the algorithm: a queue that controls the exploration order and a visited structure that ensures each node is processed only once.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    public static void bfs(List&lt;List&lt;Integer&gt;&gt; graph, int start) {<br>        // Tracks whether a node has already been visited<br>        // Prevents revisiting nodes and getting stuck in cycles<br>        boolean[] visited = new boolean[graph.size()];<br><br>        // Queue controls BFS order (FIFO = level-by-level traversal)<br>        Queue&lt;Integer&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Mark the starting node as visited and enqueue it<br>        visited[start] = true;<br>        queue.offer(start);<br><br>        // Continue until there are no more nodes to process<br>        while (!queue.isEmpty()) {<br> <br>            // Remove the next node from the front of the queue<br>            int node = queue.poll();<br><br>            // Process the current node (here: print it)<br>            System.out.print(node + &quot; &quot;);<br><br>            // Explore all neighbors of the current node<br>            for (int neighbor : graph.get(node)) {<br><br>                // Only process unvisited neighbors<br>                if (!visited[neighbor]) {<br>                    <br>                    // Mark as visited immediately to avoid duplicates in queue<br>                    // (important: prevents multiple insertions of same node)<br>                    visited[neighbor] = true;<br><br>                    // Add neighbor to queue for later processing (next BFS layer)<br>                    queue.offer(neighbor);<br>                }<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        // Number of nodes in the graph<br>        int n = 5;<br><br>        // Create adjacency list representation of the graph<br>        List&lt;List&lt;Integer&gt;&gt; graph = new ArrayList&lt;&gt;();<br>        <br>        // Initialize empty adjacency list for each node<br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        // Visualization of the graph structure:<br>        //   0<br>        //  / \<br>        // 1   2<br>        // |   |<br>        // 3   4<br>        // <br>        // Edges: 0–1, 0–2, 1–3, 2–4<br><br>        // Add edges (undirected graph)<br>        // Each connection is stored in both directions<br><br>        graph.get(0).add(1);<br>        graph.get(1).add(0);<br><br>        graph.get(0).add(2);<br>        graph.get(2).add(0);<br><br>        graph.get(1).add(3);<br>        graph.get(3).add(1);<br><br>        graph.get(2).add(4);<br>        graph.get(4).add(2);<br>        <br>        // Final adjacency list representation:<br>        // 0 → [1, 2]<br>        // 1 → [0, 3]<br>        // 2 → [0, 4]<br>        // 3 → [1]<br>        // 4 → [2]<br><br>        // Print BFS traversal starting from node 0<br>        System.out.print(&quot;BFS Traversal: &quot;);<br><br>        bfs(graph, 0);<br>    }<br>}<br><br>// Output:<br>// BFS Traversal: 0 1 2 3 4 </pre><p>This is the typical step-by-step pattern BFS follows when traversing:</p><pre>Start:        [0]<br>Visit 0 →     [1, 2]<br>Visit 1 →     [2, 3]<br>Visit 2 →     [3, 4]<br>Visit 3 →     [4]<br>Visit 4 →     [2]</pre><p>The key component that makes this process work correctly is the visited array. Without it, BFS would repeatedly revisit the same nodes, which can lead to infinite loops in graphs that contain cycles. By ensuring that each node is processed only once, BFS guarantees that it terminates correctly even in cyclic structures.</p><p>This simple constraint also produces an important emergent property: nodes are explored in order of increasing distance from the starting point. That characteristic is exactly what makes BFS the foundation for shortest path algorithms in unweighted graphs.</p><h4>2. BFS Tree Implementation</h4><p>A tree is a special type of graph with two key properties: it contains no cycles, and it has a clear hierarchical structure where each node has exactly one parent (except the root) and zero or more children.</p><p>Because of this structure, BFS becomes simpler than in general graphs. Starting from the root, each node is reached by exactly one path, so there is no risk of revisiting nodes through alternative routes. As a result, a visited set is typically not needed.</p><p>This makes the implementation more straightforward while preserving the same level-by-level traversal that defines BFS.</p><pre>import java.util.*;<br><br>// Basic tree structure<br>class TreeNode {<br>    String val;<br>    TreeNode left, right;<br><br>    TreeNode(String val) {<br>        this.val = val;<br>    }<br>}<br><br>public class Main {<br><br>    // BFS traversal for a binary tree (also called level-order traversal)<br>    public static void bfsTree(TreeNode root) {<br><br>        // Edge case: if tree is empty, nothing to traverse<br>        if (root == null) return;<br><br>        // Queue is used to process nodes level by level (FIFO order)<br>        Queue&lt;TreeNode&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Start BFS from the root node<br>        queue.offer(root);<br><br>        System.out.print(&quot;BFS (Level-Order Traversal): &quot;);<br><br>        // Continue until all nodes have been processed<br>        while (!queue.isEmpty()) {<br><br>            // Remove the next node in BFS order<br>            TreeNode node = queue.poll();<br><br>            // Process current node (here: print its value)<br>            System.out.print(node.val + &quot; &quot;);<br><br>            // Add left child to queue if it exists<br>            // This ensures it will be processed in the next levels<br>            if (node.left != null) queue.offer(node.left);<br><br>            // Add right child to queue if it exists<br>            if (node.right != null) queue.offer(node.right);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Construct the tree:<br>        //<br>        //        A<br>        //      /   \<br>        //     B     C<br>        //    / \     \<br>        //   D   E     F<br><br>        TreeNode root = new TreeNode(&quot;A&quot;);<br>        root.left = new TreeNode(&quot;B&quot;);<br>        root.right = new TreeNode(&quot;C&quot;);<br>        root.left.left = new TreeNode(&quot;D&quot;);<br>        root.left.right = new TreeNode(&quot;E&quot;);<br>        root.right.right = new TreeNode(&quot;F&quot;);<br><br>        // Run BFS<br>        bfsTree(root);<br>    }<br>}<br><br>// Output:<br>// BFS (Level-Order Traversal): A B C D E F </pre><p>This is known as <em>level-order traversal</em> — a natural fit for BFS. In this case, this is the step-by-step expansion:</p><pre>Start:        [A]<br>Step 1:       [B, C]<br>Step 2:       [C, D, E]<br>Step 3:       [D, E, F]<br>Step 4:       [E, F]<br>Step 5:       [F]<br>Step 6:       []</pre><p>BFS behaves the same algorithmically in trees and graphs, but trees simplify the implementation because the structure eliminates cycles.</p><h4>3. BFS Distance Implementation (Shortest Path)</h4><p>One of the most important applications of BFS is finding the shortest path in an unweighted graph. This works because BFS explores the graph in layers: it first visits all nodes one step away, then all nodes two steps away, and so on. As a result, the first time a node is reached, it is reached via the shortest possible path.</p><p>To use this property, we track each node along with its distance from the starting point. As BFS expands outward from the source, every newly discovered node is assigned a distance that is one more than the node it was reached from. In this way, distances are naturally computed during the traversal rather than calculated afterward.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Returns shortest distance from start to target using BFS<br>    public static int shortestPath(List&lt;List&lt;Integer&gt;&gt; graph, int start, int target) {<br>        <br>        // Tracks visited nodes to prevent revisiting and infinite loops<br>        boolean[] visited = new boolean[graph.size()];<br><br>        // Queue stores pairs: {current node, distance from start}<br>        Queue&lt;int[]&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Start BFS from the source node with distance 0<br>        queue.offer(new int[]{start, 0});<br><br>        // Process nodes in BFS order (level by level)<br>        visited[start] = true;<br><br>        while (!queue.isEmpty()) {<br><br>            // Get next node in queue<br>            int[] current = queue.poll();<br><br>            // Current node<br>            int node = current[0];<br><br>            // Distance from start<br>            int distance = current[1];<br><br>            // If we reach the target, this is guaranteed shortest path<br>            if (node == target) return distance;<br><br>            // Explore all neighboring nodes<br>            for (int neighbor : graph.get(node)) {<br><br>                // Only process unvisited neighbors<br>                if (!visited[neighbor]) {<br><br>                    // Mark as visited when adding to queue<br>                    // prevents duplicate queue entries<br>                    visited[neighbor] = true;<br><br>                    // Add neighbor with updated distance<br>                    queue.offer(new int[]{neighbor, distance + 1});<br>                }<br>            }<br>        }<br><br>        // If target is never reached, it is not connected<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        int n = 5;<br><br>        // Build adjacency list representation of an undirected graph<br>        List&lt;List&lt;Integer&gt;&gt; graph = new ArrayList&lt;&gt;();<br>        <br>        // Initialize adjacency list for each node<br>        for (int i = 0; i &lt; n; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br><br>        /*<br>            Graph structure:<br><br>                0<br>               / \<br>              1   2<br>              |   |<br>              3   4<br>        */<br><br>        // Add undirected edges (each connection stored both ways)<br>        graph.get(0).add(1); graph.get(1).add(0);<br>        graph.get(0).add(2); graph.get(2).add(0);<br>        graph.get(1).add(3); graph.get(3).add(1);<br>        graph.get(2).add(4); graph.get(4).add(2);<br><br>        int start = 0;<br>        int target = 4;<br><br>        int result = shortestPath(graph, start, target);<br><br>        System.out.println(&quot;Shortest path from &quot; + start + &quot; to &quot; + target + &quot; = &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Shortest path from 0 to 4 = 2</pre><p>This works because BFS explores nodes in order of increasing distance from the start, expanding level by level. All nodes at distance <em>d</em> are visited before any at distance <em>d + 1</em>, so the first time a node is reached, it is guaranteed to be via the shortest path.</p><p>As a result, when the target is found, that path is automatically the shortest in an unweighted graph. BFS never needs to compare alternative routes because it always prioritizes shorter paths first.</p><p>This is what makes BFS a core technique for minimum-step and shortest-path problems in unweighted graphs.</p><h4>4. BFS Grid Implementation (Shortest Path)</h4><p>At first glance, a grid may not look like a graph, but it naturally behaves like one. Each cell can be treated as a node, and each valid movement — up, down, left, or right — acts as an edge connecting that node to its neighbors.</p><p>Once viewed this way, a grid becomes just another graph structure, which makes it a perfect fit for BFS. Since each move has equal cost, BFS can systematically expand outward from a starting cell and guarantee that the first time a target cell is reached, it is through the shortest possible path in terms of number of steps.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // BFS shortest path in a grid (4-directional movement)<br>    public static int shortestPathGrid(int[][] grid, int sr, int sc, int tr, int tc) {<br>        int rows = grid.length, cols = grid[0].length;<br><br>        // Tracks visited cells to avoid revisiting and infinite loops<br>        boolean[][] visited = new boolean[rows][cols];<br><br>        // Queue stores {row, col, distance from start}<br>        Queue&lt;int[]&gt; queue = new ArrayDeque&lt;&gt;();<br>        <br>        // Start BFS from source cell with distance 0<br>        queue.offer(new int[]{sr, sc, 0});<br>        visited[sr][sc] = true;<br><br>        // Possible movement directions: down, up, right, left<br>        int[][] directions = {<br>            {1, 0}, {-1, 0}, {0, 1}, {0, -1}<br>        };<br><br>        // Process cells level by level<br>        while (!queue.isEmpty()) {<br>            <br>            // Get next cell in BFS order<br>            int[] curr = queue.poll();<br>            int r = curr[0];      // current row<br>            int c = curr[1];      // current column<br>            int dist = curr[2];   // distance from start<br><br>            // If we reach target cell, this is the shortest path<br>            if (r == tr &amp;&amp; c == tc) return dist;<br><br>            // Explore all 4 possible directions<br>            for (int[] d : directions) {<br>                <br>                int nr = r + d[0]; // next row<br>                int nc = c + d[1]; // next column<br><br>                // Check boundaries and validity of the move<br>                if (nr &gt;= 0 &amp;&amp; nc &gt;= 0 &amp;&amp;<br>                    nr &lt; rows &amp;&amp; nc &lt; cols &amp;&amp; // inside grid<br>                    grid[nr][nc] == 0 &amp;&amp;      // 0 = walkable cel<br>                    !visited[nr][nc]) {       // not visited yet<br><br>                    // Mark as visited when enqueuing<br>                    visited[nr][nc] = true;<br><br>                    // Add neighbor with updated distance<br>                    queue.offer(new int[]{nr, nc, dist + 1});<br>                }<br>            }<br>        }<br><br>        // Target not reachable<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br>        <br>        // 0 = open cell, 1 = blocked cell<br>        int[][] grid = {<br>            {0, 0, 1, 0},<br>            {1, 0, 1, 0},<br>            {0, 0, 0, 0},<br>            {0, 1, 1, 0}<br>        };<br>  <br>        // Find shortest path from (0,0) to (2,3)<br>        int result = shortestPathGrid(grid, 0, 0, 2, 3);<br><br>        System.out.println(&quot;Shortest path length: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Shortest path length: 5</pre><p>This pattern shows up constantly in practice, especially in maze solving, game pathfinding, and flood fill problems, where the goal is to explore reachable states efficiently while guaranteeing the shortest route in an unweighted grid.</p><h4>5. BFS State Space Implementation (Implicit Graph)</h4><p>Some problems don’t look like graphs at first, but they become one once you define what a “state” is and how one state can transition into another. With that abstraction in place, BFS works exactly the same way as it does for grids or adjacency list graphs.</p><p>A classic example is transforming one word into another by changing a single letter at a time, where each intermediate word must be a valid dictionary entry. This type of problem — often called a word ladder — is an example of an implicit graph, where each word is a node and each valid one-letter transformation represents an edge.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Returns minimum number of transformations from start to target<br>    public static int wordSteps(String start, String target, Set&lt;String&gt; dict) {<br>        <br>        // Queue for BFS traversal over words (states)<br>        Queue&lt;String&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Tracks visited words to avoid cycles and repeated processing<br>        Set&lt;String&gt; visited = new HashSet&lt;&gt;();<br><br>        // Start BFS from the initial word<br>        queue.offer(start);<br>        visited.add(start);<br><br>        // Tracks how many transformation steps (BFS levels) we have taken<br>        int steps = 0;<br><br>        // Standard BFS loop<br>        while (!queue.isEmpty()) {<br><br>            // Number of nodes in the current BFS level<br>            int size = queue.size();<br><br>            // Process all words at the current &quot;step&quot; level<br>            for (int i = 0; i &lt; size; i++) {<br><br>                // Get current word<br>                String word = queue.poll();<br><br>                // If we reached the target, return number of steps<br>                if (word.equals(target)) {<br>                    return steps;<br>                }<br><br>                // Try all dictionary words as possible next states<br>                for (String next : dict) {<br><br>                    // Only consider unvisited words that differ by one letter<br>                    if (!visited.contains(next) &amp;&amp; oneLetterDiff(word, next)) {<br>                        <br>                        // Mark as visited when adding to queue<br>                        visited.add(next);<br><br>                        // Add next state to BFS queue<br>                        queue.offer(next);<br>                    }<br>                }<br>            }<br><br>            // After finishing one level, increment step count<br>            steps++;<br>        }<br><br>        // Target not reachable<br>        return -1;<br>    }<br><br>    // Checks if two words differ by exactly one letter<br>    private static boolean oneLetterDiff(String a, String b) {<br>        if (a.length() != b.length()) return false;<br><br>        int diff = 0;<br><br>        // Count character differences<br>        for (int i = 0; i &lt; a.length(); i++) {<br>            if (a.charAt(i) != b.charAt(i)) {<br>                diff++;<br><br>                // More than one difference → not valid transformation<br>                if (diff &gt; 1) return false;<br>            }<br>        }<br><br>        // Valid only if exactly one letter differs<br>        return diff == 1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Dictionary of valid words (graph nodes)<br>        Set&lt;String&gt; dict = new HashSet&lt;&gt;(Arrays.asList(<br>            &quot;cold&quot;, &quot;cord&quot;, &quot;card&quot;, &quot;ward&quot;, &quot;warm&quot;<br>        ));<br><br>        String start = &quot;cold&quot;;<br>        String target = &quot;warm&quot;;<br><br>        // Run BFS word transformation search<br>        int result = wordSteps(start, target, dict);<br><br>        System.out.println(&quot;Minimum transformation steps: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum transformation steps: 4</pre><p>In this pattern, each state is treated as a node in an implicit graph, and each valid transformation (such as changing one letter while staying in a dictionary) represents an edge between nodes. There is no explicit adjacency list or matrix — instead, connections are generated as BFS explores the search space.</p><p>Even without being explicitly built, the structure is still a graph, and BFS works the same way. The key idea is that BFS only needs a state definition and a way to move between states. Once those exist, it applies naturally — whether the graph is explicit or implicit.</p><h4>6. BFS Object-Based Graph Implementation</h4><p>In real applications, graphs are rarely made of simple integers or arrays. Instead, you work with domain objects such as users, pages, products, or services, where relationships are already embedded in the data model. The graph is still there — it is just represented implicitly through object relationships rather than explicitly defined.</p><p>A social network is a natural example. Each user can be treated as a node, and each friendship becomes an edge connecting two nodes. From this perspective, BFS provides a straightforward way to explore how influence, content, or connections spread outward from a given starting user.</p><pre>import java.util.*;<br><br>// Represents a user in a social network graph<br>class User {<br>    String name;<br><br>    // List of direct connections (edges) to other users<br>    List&lt;User&gt; friends = new ArrayList&lt;&gt;();<br><br>    User(String name) {<br>        this.name = name;<br>    }<br>}<br><br>public class Main {<br><br>    // BFS traversal starting from a given user<br>    public static void bfs(User start) {<br><br>        // Tracks visited users to avoid cycles and repeated visits<br>        Set&lt;User&gt; visited = new HashSet&lt;&gt;();<br><br>        // Queue controls BFS order (level-by-level exploration)<br>        Queue&lt;User&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Start BFS from the initial user<br>        visited.add(start);<br>        queue.offer(start);<br><br>        // Process users in BFS order<br>        while (!queue.isEmpty()) {<br><br>            // Get next user to process<br>            User current = queue.poll();<br><br>            // Visit action (can be replaced with any processing logic)<br>            System.out.println(&quot;Visiting: &quot; + current.name);<br><br>            // Explore all direct friends (neighbors)<br>            for (User friend : current.friends) {<br><br>                // Only visit unvisited users<br>                if (!visited.contains(friend)) {<br><br>                    // Mark as visited when enqueuing to avoid duplicates<br>                    visited.add(friend);<br><br>                    // Add friend to BFS queue for later processing<br>                    queue.offer(friend);<br>                    System.out.println(&quot;Discovered: &quot; + friend.name + &quot; (added to queue)&quot;);<br>                } else {<br>                    System.out.println(&quot;Skipped (already visited): &quot; + friend.name);<br>                }<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Create users (nodes in the graph)<br>        User alice = new User(&quot;Alice&quot;);<br>        User bob = new User(&quot;Bob&quot;);<br>        User carol = new User(&quot;Carol&quot;);<br>        User dave = new User(&quot;Dave&quot;);<br><br>        // Build friendship connections (edges in the graph)<br>        alice.friends.add(bob);<br>        alice.friends.add(carol);<br>        bob.friends.add(dave);<br>        carol.friends.add(dave);<br><br>        // Run BFS starting from Alice<br>        bfs(alice);<br>    }<br>}<br><br>// Output:<br>// Visiting: Alice<br>// Discovered: Bob (added to queue)<br>// Discovered: Carol (added to queue)<br>// Visiting: Bob<br>// Discovered: Dave (added to queue)<br>// Visiting: Carol<br>// Skipped (already visited): Dave<br>// Visiting: Dave</pre><p>This pattern appears frequently in systems such as social networks, recommendation engines, and graph-based search problems. The key shift is that you are no longer explicitly constructing a graph — instead, you are traversing relationships that already exist within your objects. Despite the different representation, BFS itself remains unchanged; only the way the graph is modeled differs.</p><h3>Practical Examples💡</h3><p>BFS is not just a theoretical algorithm — it shows up everywhere we need to explore things step by step in increasing “distance” from a starting point. The key pattern is always the same: we expand outward evenly, ensuring the closest possibilities are explored first.</p><h4>1. Shortest Path in Unweighted Grids (Robot Warehouse Navigation)</h4><p>One of the most classic real-world uses of BFS is finding the shortest path in environments where every move has the same cost.</p><p>A common example is a grid-based navigation system, such as a simple robot moving through a structured floor plan or a maze-like environment. The robot can move one step at a time in four directions, and each move has equal cost.</p><p>In this type of problem, BFS is ideal because it explores all reachable positions level by level. The first time we reach the destination, we are guaranteed to have found the minimum number of steps.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // Computes shortest path in a grid-based warehouse using BFS (unweighted graph)<br>    public static int shortestPath(int[][] warehouse, int sr, int sc, int tr, int tc) {<br><br>        int rows = warehouse.length;<br>        int cols = warehouse[0].length;<br><br>        // Tracks visited cells to avoid revisiting and infinite loops<br>        boolean[][] visited = new boolean[rows][cols];<br><br>        // BFS queue stores: (row, col, distance from start)<br>        Queue&lt;int[]&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Initialize BFS from the starting position (Loading Dock)<br>        queue.offer(new int[]{sr, sc, 0});<br>        visited[sr][sc] = true;<br><br>        // Possible robot movements in the grid (4-directional movement)<br>        // Each move represents traveling along warehouse aisles<br>        int[][] directions = {<br>                {1, 0},   // move down<br>                {-1, 0},  // move up<br>                {0, 1},   // move right<br>                {0, -1}   // move left<br>        };<br><br>        // Standard BFS traversal (guarantees shortest path in unweighted grid)<br>        while (!queue.isEmpty()) {<br><br>            int[] current = queue.poll();<br><br>            int r = current[0];     // current row<br>            int c = current[1];     // current column<br>            int steps = current[2]; // distance from start<br><br>            // Target reached (Packing Station)<br>            if (r == tr &amp;&amp; c == tc) {<br>                return steps;<br>            }<br><br>            // Explore all adjacent aisle cells<br>            for (int[] dir : directions) {<br><br>                int nr = r + dir[0]; // next row<br>                int nc = c + dir[1]; // next column<br><br>                // Validate candidate move:<br>                // 1. inside grid bounds<br>                // 2. not blocked by storage racks (1 = obstacle)<br>                // 3. not visited before<br>                if (nr &gt;= 0 &amp;&amp; nc &gt;= 0 &amp;&amp;<br>                    nr &lt; rows &amp;&amp; nc &lt; cols &amp;&amp;<br>                    warehouse[nr][nc] == 0 &amp;&amp;<br>                    !visited[nr][nc]) {<br><br>                    visited[nr][nc] = true; // mark immediately to prevent re-queueing<br>                    queue.offer(new int[]{nr, nc, steps + 1}); // enqueue next state<br>                }<br>            }<br>        }<br><br>        // If BFS completes without reaching target, no valid path exists<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Warehouse grid representation:<br>        // 0 = free aisle (traversable space)<br>        // 1 = storage racks / obstacles (blocked cells)<br><br>        int[][] warehouse = {<br>                // 0  1  2  3  4  5  6<br>                {0, 0, 1, 0, 0, 0, 0},  // Loading dock area (start region)<br>                {1, 0, 1, 0, 1, 1, 0},  // Dense rack layout with narrow gaps<br>                {0, 0, 0, 0, 0, 1, 0},  // Main corridor (high connectivity)<br>                {0, 1, 1, 1, 0, 0, 0},  // Bottleneck passage between racks<br>                {0, 0, 0, 1, 0, 1, 0},  // Mixed obstruction zone<br>                {1, 1, 0, 0, 0, 0, 0},  // Approach corridor to destination<br>                {0, 0, 0, 1, 1, 0, 0}   // Packing station area (goal region)<br>        };<br><br>        // Start position: Loading Dock<br>        int startRow = 0, startCol = 0;<br><br>        // Target position: Packing Station<br>        int targetRow = 6, targetCol = 6;<br><br>        int result = shortestPath(warehouse, startRow, startCol, targetRow, targetCol);<br><br>        System.out.println(&quot;Minimum moves from Loading Dock to Packing Station: &quot; + result);<br>    }<br>}<br><br>// Output:<br>// Minimum moves from Loading Dock to Packing Station: 12</pre><p>The key idea remains the same: each queue entry carries both the position and the number of steps taken so far. This allows BFS to naturally expand outward in layers and guarantees the shortest path is found the moment the target is reached.</p><h4>2. Web Crawlers and Search Engines</h4><p>Web crawling is one of the most natural real-world applications of BFS. The web can be modeled as a directed graph where:</p><ul><li>each webpage is a node</li><li>each hyperlink is a directed edge to another page</li></ul><p>Search engines and crawlers typically start from a seed URL and explore the web in a breadth-first manner. This means they first discover pages that are directly linked from the starting page, then move to pages linked from those pages, and so on.</p><p>This level-by-level exploration is important because it prioritizes pages that are “closer” in link distance to the source before expanding into deeper parts of the web graph.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    // BFS-based web crawler starting from a seed URL<br>    public static void crawl(String startUrl, Map&lt;String, List&lt;String&gt;&gt; webGraph) {<br><br>        // Queue controls BFS traversal over webpages (level-by-level exploration)<br>        Queue&lt;String&gt; queue = new ArrayDeque&lt;&gt;();<br><br>        // Visited set prevents revisiting the same page (avoids infinite loops)<br>        Set&lt;String&gt; visited = new HashSet&lt;&gt;();<br><br>        // Start crawling from the seed page<br>        queue.offer(startUrl);<br>        visited.add(startUrl);<br><br>        System.out.println(&quot;Starting crawl from: &quot; + startUrl + &quot;\n&quot;);<br><br>        // Standard BFS loop<br>        while (!queue.isEmpty()) {<br><br>            // Get next page to process<br>            String page = queue.poll();<br><br>            System.out.println(&quot;Crawling: &quot; + page);<br><br>            // Get all outgoing links from the current page<br>            // If page has no links, return empty list safely<br>            List&lt;String&gt; links = webGraph.getOrDefault(page, Collections.emptyList());<br><br>            // Explore all linked pages<br>            for (String link : links) {<br><br>                // Only visit pages we haven&#39;t seen before<br>                if (!visited.contains(link)) {<br><br>                    visited.add(link);   // mark as discovered<br>                    queue.offer(link);   // add to next BFS layer<br><br>                    System.out.println(&quot;Discovered link: &quot; + link);<br>                }<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        // Simulated web graph:<br>        // Each node represents a webpage<br>        // Each edge represents a hyperlink between pages<br>        Map&lt;String, List&lt;String&gt;&gt; webGraph = new HashMap&lt;&gt;();<br><br>        webGraph.put(&quot;A&quot;, Arrays.asList(&quot;B&quot;, &quot;C&quot;));<br>        webGraph.put(&quot;B&quot;, Arrays.asList(&quot;D&quot;, &quot;E&quot;));<br>        webGraph.put(&quot;C&quot;, Arrays.asList(&quot;F&quot;));<br>        webGraph.put(&quot;D&quot;, Arrays.asList(&quot;G&quot;));<br>        webGraph.put(&quot;E&quot;, Arrays.asList(&quot;G&quot;, &quot;H&quot;));<br>        webGraph.put(&quot;F&quot;, Arrays.asList(&quot;I&quot;));<br>        webGraph.put(&quot;G&quot;, Collections.emptyList());<br>        webGraph.put(&quot;H&quot;, Arrays.asList(&quot;I&quot;));<br>        webGraph.put(&quot;I&quot;, Collections.emptyList());<br><br>        // Start crawling from seed page A<br>        crawl(&quot;A&quot;, webGraph);<br>    }<br>}<br><br>// Output:<br>// Starting crawl from: A<br>// <br>// Crawling: A<br>// Discovered link: B<br>// Discovered link: C<br>// Crawling: B<br>// Discovered link: D<br>// Discovered link: E<br>// Crawling: C<br>// Discovered link: F<br>// Crawling: D<br>// Discovered link: G<br>// Crawling: E<br>// Discovered link: H<br>// Crawling: F<br>// Discovered link: I<br>// Crawling: G<br>// Crawling: H<br>// Crawling: I</pre><p>In this setup, BFS ensures that pages directly linked from the seed URL are discovered first, then pages one hop further away are explored, and deeper pages are only reached after closer ones.</p><p>This produces a structured, level-by-level exploration of the web graph, which is exactly why BFS is a natural foundation for basic web crawling systems.</p><h3>Conclusion 📣</h3><p>Breadth-First Search is one of those foundational algorithms that appears simple at first glance, yet powers a surprisingly wide range of real-world systems. Whether you are navigating a grid, traversing a graph, crawling the web, or exploring abstract state spaces, BFS provides a consistent and reliable strategy: explore outward in layers, one level at a time.</p><p>Across all the examples in this article, the same core pattern appears repeatedly — a queue to control exploration order, a visited structure to prevent repetition, and a step-by-step expansion that guarantees the closest states are processed first. This shared structure is what makes BFS so versatile. It doesn’t depend on the specific domain; it depends only on how the problem can be represented as connected states.</p><p>At the same time, BFS is not a universal solution. Its memory requirements can grow quickly, and it is only optimal when all steps have equal cost. In weighted or extremely large search spaces, more specialized algorithms may be better suited.</p><p>Still, BFS remains an essential tool in any developer’s problem-solving toolkit. It not only solves practical shortest-path and exploration problems efficiently, but also builds intuition for how complex systems can be modeled as graphs — often the first step toward understanding more advanced algorithms in pathfinding, AI, and network analysis.</p><p>In short, BFS is less about code and more about perspective: once you learn to see problems as layers of connected states, a wide range of challenges suddenly becomes much easier to reason about and solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9801a76ba137" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Search Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/linear-search-algorithm-in-java-learn-with-practical-examples-491adb91bb1f?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/491adb91bb1f</guid>
            <category><![CDATA[linear-search]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Sat, 02 May 2026 17:31:19 GMT</pubDate>
            <atom:updated>2026-05-02T17:31:19.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpK-bzsIRR8R5fN3N4WVVw.png" /></figure><p>Linear Search is one of the simplest and most fundamental searching algorithms in computer science. Unlike more advanced techniques such as <a href="https://medium.com/@robinviktorsson/binary-search-algorithm-in-java-learn-with-practical-examples-9caf5dbf005a">binary search</a> or <a href="https://medium.com/@robinviktorsson/interpolation-search-algorithm-in-java-learn-with-practical-examples-82178015fc40">interpolation search</a>, it does not depend on sorted data or complex logic. Instead, it follows a direct approach: it checks each element one by one until the target value is found or the dataset ends.</p><p>Although it is not the most efficient algorithm in terms of performance, its clarity and ease of implementation make it an important foundation for learning how search algorithms work. It also helps build intuition for how more advanced techniques improve upon this basic idea.</p><p>In this article, we’ll explore how Linear Search works, implement it in Java, and examine both its strengths and its limitations in real-world scenarios.</p><h3>What Is Linear Search? 🔍</h3><p>Linear Search (also known as sequential search) is one of the first searching techniques developers learn in computer science. It is a basic algorithm used to find a target value within a list or array, and it introduces the fundamental idea of searching by inspection.</p><p>It works by iterating through each element from start to finish until the desired value is found or the entire list has been checked.</p><p>Here’s the core idea:</p><ul><li>Start from the first element</li><li>Compare it with the target</li><li>If equal → done</li><li>If not → move to the next element</li><li>Repeat until the element is found or the list ends</li></ul><p>You can think of it like looking for a name in an unsorted contact list — you go through each entry one by one until you find what you’re looking for.</p><h3>When Should You Use Linear Search? 🧐</h3><p>Linear search makes the most sense in situations where simplicity and flexibility matter more than raw speed. It works especially well when the dataset is small, because checking each element one by one doesn’t take much time anyway. It’s also a natural fit when the data isn’t sorted and you don’t want the extra overhead of organizing it first.</p><p>Another good use case is when you only need to perform a single search. If you’re not going to reuse the data structure repeatedly, spending time sorting or indexing can actually cost more effort than just scanning through the data once. In those moments, linear search is often the more practical option.</p><p>Its performance varies depending on where the target appears. In the best case, when the element is the very first one checked, the time complexity is <a href="https://medium.com/gitconnected/a-simple-guide-to-time-complexity-for-software-engineers-without-the-headache-36101843633c">O(1)</a>, meaning the result is found immediately. In the worst case, when the element is at the end of the dataset or not present at all, the time complexity becomes O(n), since every element must be examined. This linear growth in runtime is exactly why the algorithm doesn’t scale well for large datasets.</p><p>Even so, in real-world scenarios where data is modest in size or constantly changing, linear search remains a reliable and straightforward solution.</p><h3>From Theory to Practice 🛠️</h3><p>Before implementing Linear Search manually, it’s worth noting that Java provides built-in methods like contains() for collections. In sequential collections such as ArrayList or LinkedList, this method internally performs a linear search. Understanding this helps you make more informed decisions about when simplicity is sufficient and when a different data structure might offer better performance.</p><h4>1. Core Implementation (Iterative)</h4><p>Let’s start with a basic iterative implementation of Linear Search in Java. This is the most common and beginner-friendly way to understand how the algorithm works in practice.</p><pre>public class Main {<br><br>    public static int linearSearch(int[] arr, int target) {<br><br>        // Traverse the array element by element<br>        for (int i = 0; i &lt; arr.length; i++) {<br><br>            // Check if current element matches target<br>            if (arr[i] == target) {<br>                return i;<br>            }<br>        }<br><br>        // Target not found<br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {4, 2, 7, 1, 9, 3};<br><br>        int result = linearSearch(arr, 7);<br><br>        if (result != -1) {<br>            System.out.println(&quot;Element found at index: &quot; + result);<br>        } else {<br>            System.out.println(&quot;Element not found.&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Element found at index: 2</pre><p>This implementation demonstrates the most direct form of Linear Search: a simple traversal of the array from start to finish. The algorithm begins at index 0 and checks each element one by one, comparing it to the target value. If a match is found, it immediately returns the current index, which also stops further execution early.</p><p>If the loop completes without finding the target, the method returns -1 to indicate that the element is not present in the array.</p><p>What makes this approach so important is its simplicity. There is no need for additional data structures, no recursion, and no requirement for the array to be sorted. The logic relies entirely on a single loop and direct comparison, making it easy to read, debug, and understand.</p><h4>2. Recursive Implementation</h4><p>Although less common in practice, Linear Search can also be implemented using recursion. This version helps illustrate how the same problem can be solved by breaking it down into smaller subproblems, where each recursive call handles a single element.</p><pre>public class Main {<br><br>    public static int linearSearch(int[] arr, int target, int index) {<br><br>        // Base case: reached end of array<br>        if (index &gt;= arr.length) {<br>            return -1;<br>        }<br><br>        // Check current element<br>        if (arr[index] == target) {<br>            return index;<br>        }<br><br>        // Recursive call for next index<br>        return linearSearch(arr, target, index + 1);<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {4, 2, 7, 1, 9, 3};<br><br>        int result = linearSearch(arr, 7, 0);<br><br>        if (result != -1) {<br>            System.out.println(&quot;Element found at index: &quot; + result);<br>        } else {<br>            System.out.println(&quot;Element not found.&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Element found at index: 2</pre><p>In this recursive version, the algorithm starts at index 0 and checks one element at a time. Each function call is responsible for evaluating a single position in the array. If the current element matches the target, the function immediately returns the index. If not, it calls itself again with the next index, effectively moving forward through the array step by step.</p><p>The recursion stops when either the target is found or the index goes beyond the last element, which serves as the base case.</p><p>While this approach is useful for understanding how recursion works, it is generally less practical than the iterative version. Each recursive call adds overhead to the call stack, which can impact performance and memory usage, especially for large arrays. For this reason, the iterative implementation is preferred in most real-world applications, even though both versions have the same O(n) time complexity.</p><h4>3. Linear Search with Objects</h4><p>Linear Search is not limited to primitive data types like integers — it can also be applied to objects. This makes it especially useful in real-world applications where data is usually stored in structured forms such as classes and collections.</p><p>In this example, we define a simple Product class and perform a search based on a property (name).</p><pre>import java.util.*;<br><br>class Product {<br>    String name;<br>    double price;<br>    Product(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br>}<br>public class Main {<br>    public static int linearSearch(List&lt;Product&gt; list, String targetName) {<br>        for (int i = 0; i &lt; list.size(); i++) {<br>            if (list.get(i).name.equals(targetName)) {<br>                return i;<br>            }<br>        }<br>        return -1;<br>    }<br>    public static void main(String[] args) {<br>        List&lt;Product&gt; products = new ArrayList&lt;&gt;();<br>        products.add(new Product(&quot;Book&quot;, 12.99));<br>        products.add(new Product(&quot;Laptop&quot;, 999.99));<br>        products.add(new Product(&quot;Pen&quot;, 1.49));<br>        products.add(new Product(&quot;Phone&quot;, 599.99));<br><br>        int index = linearSearch(products, &quot;Phone&quot;);<br>        <br>        if (index != -1) {<br>            System.out.println(&quot;Found: &quot; + products.get(index).name);<br>        } else {<br>            System.out.println(&quot;Not found&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Found: Phone</pre><p>In this version, Linear Search is applied to a list of objects instead of simple values. The algorithm iterates through each Product in the list and compares the name field with the target value. If a match is found, it returns the index of that object in the list.</p><p>This demonstrates an important concept: Linear Search is not tied to a specific data type. It can operate on any structure as long as you can define a comparison condition.</p><p>One of the key advantages here is that no sorting or pre-processing is required. You can search based on any property — such as name, price, or ID — without modifying the underlying data structure. This makes Linear Search particularly useful in dynamic systems where objects are frequently added, removed, or updated.</p><p>Its flexibility allows it to work with arrays, lists, and complex objects alike, without requiring random access or any special constraints. However, this flexibility comes with a trade-off. As the dataset grows, performance becomes a limitation because Linear Search must examine each element individually and cannot skip or optimize based on structure.</p><h3>Where Linear Search Becomes Useful 💡</h3><p>Despite its simplicity, Linear Search appears in many practical scenarios where its straightforward behavior is actually an advantage rather than a limitation.</p><h4>1. Small Datasets and Quick Checks</h4><p>When working with small collections, the performance difference between Linear Search and more advanced algorithms is often negligible. In such cases, the overhead of more complex solutions is not justified, and a simple scan is usually the most practical approach.</p><pre>public class Main {<br><br>    public static boolean contains(int[] arr, int target) {<br>        for (int num : arr) {<br>            if (num == target) return true;<br>        }<br><br>        return false;<br>    }<br><br>    public static void main(String[] args) {<br>        int[] values = {5, 8, 12, 20};<br><br>        System.out.println(contains(values, 12));<br>    }<br>}<br><br>// Output:<br>// true</pre><p>In situations like this, simplicity is more valuable than optimization.</p><h4>2. Unsorted or dynamic data</h4><p>In systems where data changes frequently, maintaining a sorted structure can be expensive and impractical. Inserts, deletions, and updates would constantly require reordering or restructuring.</p><p>Linear Search avoids this entirely by operating directly on the raw data, without any preprocessing requirements. This makes it a natural fit for dynamic datasets where the content is continuously evolving.</p><pre>import java.util.*;<br><br>public class Main {<br><br>    public static boolean contains(List&lt;Integer&gt; list, int target) {<br><br>        for (int value : list) {<br>            if (value == target) return true;<br>        }<br><br>        return false;<br>    }<br><br>    public static void main(String[] args) {<br><br>        List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();<br>        numbers.add(10);<br>        numbers.add(25);<br>        numbers.add(7);<br>        numbers.add(30);<br><br>        System.out.println(contains(numbers, 7));<br>    }<br>}<br><br>// Output:<br>// true</pre><h4>3. Streaming and real-time data</h4><p>When working with streaming data such as logs, sensor readings, or live event feeds, sorting the data beforehand is often not possible or would introduce unacceptable delay.</p><p>Linear Search works well here because it allows immediate processing: each incoming value can be checked on the spot, and actions can be triggered instantly based on the result.</p><pre>public class Main {<br><br>    public static void processStream(int[] stream, int target) {<br><br>        for (int value : stream) {<br>            if (value == target) {<br>                System.out.println(&quot;Target found: &quot; + value);<br>                return;<br>            }<br>        }<br><br>        System.out.println(&quot;Target not found in stream.&quot;);<br>    }<br><br>    public static void main(String[] args) {<br><br>        int[] sensorData = {3, 15, 8, 22, 5};<br><br>        processStream(sensorData, 22);<br>    }<br>}<br><br>// Output:<br>// Target found: 22</pre><h4>4. Fallback mechanism</h4><p>Even in systems that primarily rely on more advanced search techniques, Linear Search often serves as a reliable fallback when the dataset is small, the structure is unknown, or edge cases need a simple and predictable solution. It acts as a safe default when no assumptions can be made about the data.</p><h3>Conclusion 📣</h3><p>Linear Search may be one of the simplest algorithms in computer science, but its value lies precisely in that simplicity. By checking each element sequentially, it avoids any dependency on sorting, indexing, or specialized data structures, making it easy to understand, implement, and apply in a wide range of scenarios.</p><p>Throughout this article, we saw that Linear Search performs reliably across both primitive data types and objects, whether implemented iteratively or recursively. In Java, it is also closely reflected in built-in methods like contains(), which often rely on the same underlying idea depending on the collection type. This connection reinforces an important lesson: even high-level abstractions are frequently built on fundamental algorithms like linear search.</p><p>At the same time, we also learned its limitations. With a time complexity of O(n) in the worst case, Linear Search does not scale efficiently for large datasets. It cannot exploit structure in the data or reduce the search space, which is why more advanced algorithms become necessary as performance demands increase.</p><p>However, this does not diminish its importance. In fact, Linear Search remains highly relevant in real-world development — especially when working with small datasets, dynamic or frequently changing data, real-time streams, or as a dependable fallback when no assumptions can be made about structure or ordering.</p><p>Ultimately, Linear Search serves as a foundational concept: it builds intuition for algorithmic thinking and provides a baseline for understanding why more advanced search techniques exist. Mastering it is not about performance optimization, but about developing a clear understanding of how searching works at its most fundamental level.</p><p>Happy coding! 😃</p><p>🙏 <strong>Thanks</strong> for reading to the end! If you have any questions, feel free to drop a comment below.</p><p>If you enjoyed this article, follow me on medium or social media — I’d love to connect and follow you back:</p><ul><li><a href="https://x.com/RobinViktorsson">Robin Viktorsson (@RobinViktorsson) / X</a></li><li><a href="https://mastodon.social/@robinviktorsson">Robin Viktorsson (@robinviktorsson@mastodon.social) — Mastodon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491adb91bb1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jump Search Algorithm in Java: Learn with Practical Examples]]></title>
            <link>https://medium.com/@robinviktorsson/jump-search-algorithm-in-java-learn-with-practical-examples-633876051750?source=rss-96f784843044------2</link>
            <guid isPermaLink="false">https://medium.com/p/633876051750</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[jump-search]]></category>
            <category><![CDATA[search-algorithm]]></category>
            <dc:creator><![CDATA[Robin Viktorsson]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 12:01:02 GMT</pubDate>
            <atom:updated>2026-04-29T12:01:02.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjS8Y86f3JXVRVYV9xM2rQ.png" /></figure><p>Jump Search is a lesser-known, but highly practical searching algorithm that sits somewhere between Linear Search and Binary Search. While it doesn’t achieve the same logarithmic performance as <a href="https://medium.com/@robinviktorsson/binary-search-algorithm-in-java-learn-with-practical-examples-9caf5dbf005a">Binary Search</a>, it introduces an interesting optimization: instead of checking every element one by one, it jumps ahead in fixed steps to quickly narrow down where a value might be.</p><p>This approach is especially useful for sorted datasets where binary search may be less convenient due to access patterns or implementation constraints. For example, when data is stored sequentially and random access is costly, repeatedly splitting the range becomes less practical. Jump Search instead moves forward in fixed increments and switches to a linear scan after passing the likely target region, making it simpler and better aligned with sequential access.</p><p>Overall, it balances efficiency and simplicity — reducing comparisons compared to linear search while remaining easy to implement. Though not as fast as binary search, its predictable behavior makes it a solid choice in certain constrained scenarios.</p><p>In this article, we’ll explore how Jump Search works, implement it in Java, and understand when it’s the right tool for the job.</p><h3>What Is Jump Search? 🔍</h3><p>Jump Search is an algorithm used to find a target value in a sorted array by skipping ahead in blocks instead of scanning sequentially. It works by jumping forward in fixed steps (typically √n) until the relevant block is found, then performing a linear search within that block.</p><p>For example, if we search for value 9 in the array:</p><pre>[1, 3, 5, 7, 9, 11, 13, 15]</pre><p>The array has 8 elements, so the step size is √8 ≈ 2. Lets jump through the array in steps of 2:</p><ul><li>Index 1 → value 3 (still &lt; 9, keep jumping)</li><li>Index 3 → value 7 (still &lt; 9, keep jumping)</li><li>Index 5 → value 11 (&gt; 9, we’ve gone too far)</li></ul><p>We stop here and know the target must be in the previous block (between index 3 and 5). Now we perform a linear scan in that range:</p><ul><li>Index 3 → 7 (not a match)</li><li>Index 4 → 9 (<strong>found!</strong>)</li><li>Index 5 → not needed anymore</li></ul><p>Think of it like flipping through a learning book to find a specific section. Instead of reading every page one by one (linear search), or repeatedly narrowing the search by opening the middle of the remaining pages (binary search), you move forward in fixed jumps — say every 10 pages — until you pass the section you’re looking for, then go back and scan page by page within that small range.</p><h3>When Should You Use Jump Search? 🧐</h3><p>Jump Search works best when your data is already sorted and you want something simpler than binary search without fully sacrificing efficiency. It tends to fit well in situations where you are working with arrays or other structures that allow direct access to elements, since the algorithm relies on jumping to specific indices rather than traversing sequentially like a linked list.</p><p>In terms of performance, the best case is <a href="https://medium.com/gitconnected/a-simple-guide-to-time-complexity-for-software-engineers-without-the-headache-36101843633c">O(1)</a> because the algorithm might find the target immediately. This happens if the element you’re searching for is at the first checked position — either the very first element or the first jump lands exactly on it. In that case, no further jumps or linear scanning are needed, so the work is constant.</p><p>The worst case is O(√n) because of two phases: jumping and linear scanning. You make about √n jumps (since the step size is √n), and in the worst case you also do up to √n comparisons during the final linear scan within a block. Together, this still results in O(√n) time.</p><p>In practice, Jump Search shines in medium-sized datasets where the overhead of more complex logic like binary search may not be worth it, or where a simple and predictable access pattern is preferred. It is often chosen when readability and straightforward implementation are more important than squeezing out maximum theoretical performance.</p><p>However, it does come with trade-offs. The data must be sorted beforehand, and for large datasets it is generally outperformed by binary search. Additionally, even after the jump phase, it still relies on a linear scan within the identified block, which can add extra cost depending on where the target value lies.</p><h3>From Theory to Practice 🛠️</h3><p>Java doesn’t provide a built-in Jump Search method, so we’ll implement it from scratch.</p><h4>1. Core Implementation</h4><p>Here’s a clean and practical implementation in Java:</p><pre>public class Main {<br><br>    public static int jumpSearch(int[] arr, int target) {<br>        int n = arr.length;<br><br>        // Optimal block size = √n<br>        int step = (int) Math.sqrt(n);<br><br>        int prev = 0;<br><br>        // Jump ahead in blocks<br>        while (arr[Math.min(step, n) - 1] &lt; target) {<br>            prev = step;<br>            step += (int) Math.sqrt(n);<br><br>            // If we exceed array bounds, target is not present<br>            if (prev &gt;= n) {<br>                return -1;<br>            }<br>        }<br><br>        // Linear search within the identified block<br>        while (arr[prev] &lt; target) {<br>            prev++;<br><br>            if (prev == Math.min(step, n)) {<br>                return -1;<br>            }<br>        }<br><br>        // Target found<br>        if (arr[prev] == target) {<br>            return prev;<br>        }<br><br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {1, 3, 5, 7, 9, 11, 13, 15};<br><br>        int result = jumpSearch(arr, 9);<br><br>        if (result != -1) {<br>            System.out.println(&quot;Element found at index: &quot; + result);<br>        } else {<br>            System.out.println(&quot;Element not found.&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Element found at index: 4</pre><p>This implementation follows the two core phases of Jump Search: it first jumps ahead in blocks of size √n to quickly narrow down the search range, then performs a linear scan within that block to locate the exact element. This combination reduces unnecessary comparisons while keeping the algorithm simple and predictable.</p><h4>2. The Trade-Off: Simplicity vs Performance</h4><p>Jump Search is a good example of a trade-off algorithm, where you gain simplicity and predictability at the cost of some performance.</p><p>It is relatively easy to implement and follows a clear, predictable access pattern. Compared to linear search, it reduces the number of checks by skipping ahead in fixed steps, and it avoids recursion or any complex decision-making logic.</p><p>However, these benefits come with limitations. It is still slower than binary search, depends on the data being sorted, and once it narrows down a region, it still relies on a linear scan within that block.</p><p>The key insight is that Jump Search fits a middle ground: it’s useful when you want something more efficient than linear search, but simpler and more straightforward than binary search.</p><h4>3. Jump Search with Objects</h4><p>Jump Search can also be applied to objects — as long as they are sorted by a key. The idea remains the same: instead of working with raw values, you compare based on a specific attribute.</p><p>Here’s an example that demonstrates how you can search for products by price:</p><pre>import java.util.*;<br><br>class Product {<br>    String name;<br>    double price;<br>    Product(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br>}<br>public class Main {<br>    public static int jumpSearch(List&lt;Product&gt; list, double targetPrice) {<br>        int n = list.size();<br>        int step = (int) Math.sqrt(n);<br>        int prev = 0;<br><br>        // Jump through blocks<br>        while (list.get(Math.min(step, n) - 1).price &lt; targetPrice) {<br>            prev = step;<br>            step += (int) Math.sqrt(n);<br>            if (prev &gt;= n) {<br>                return -1;<br>            }<br>        }<br><br>        // Linear scan inside block<br>        while (list.get(prev).price &lt; targetPrice) {<br>            prev++;<br>            if (prev == Math.min(step, n)) {<br>                return -1;<br>            }<br>        }<br><br>        // Match found<br>        if (Math.abs(list.get(prev).price - targetPrice) &lt; 1e-9) {<br>            return prev;<br>        }<br><br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br>        List&lt;Product&gt; products = new ArrayList&lt;&gt;(Arrays.asList(<br>            new Product(&quot;Pen&quot;, 1.5),<br>            new Product(&quot;Notebook&quot;, 3.0),<br>            new Product(&quot;Mouse&quot;, 8.0),<br>            new Product(&quot;Keyboard&quot;, 15.0),<br>            new Product(&quot;Monitor&quot;, 120.0)<br>        ));<br>        double target = 15.0;<br>        int index = jumpSearch(products, target);<br>        if (index != -1) {<br>            System.out.println(&quot;Found: &quot; + products.get(index).name);<br>        } else {<br>            System.out.println(&quot;Not found&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Found: Keyboard</pre><h3>Where Jump Search Becomes Useful 💡</h3><p>Jump Search isn’t a general replacement for faster algorithms like binary search. Its value shows up in more practical, system-level scenarios where how data is accessed matters just as much as how quickly it is searched. In these cases, predictable movement through data can be more important than minimizing comparisons.</p><h4>1. Paginated or chunked data systems (API or database-style access)</h4><p>A strong real-world use case is working with paginated APIs or chunked data sources, where data is accessed in fixed-size pages (for example, 100 records per request). You can’t jump directly to any arbitrary index cheaply — instead, you move page by page.</p><p>In such systems, algorithms such as binary search can become inefficient because it requires frequent back-and-forth jumps (e.g., page 50 → page 25 → page 37), which leads to repeated requests and higher latency. Jump Search aligns better with this model by moving forward in larger, predictable steps, then scanning locally once the target range is passed.</p><pre>public class Main {<br><br>    // Simulated &quot;API page size&quot;<br>    static int PAGE_SIZE = 5;<br><br>    public static int jumpSearch(int[] arr, int target) {<br>        int n = arr.length;<br>        int step = (int) Math.sqrt(n);<br>        int prev = 0;<br><br>        // Jump through &quot;pages&quot;<br>        while (prev &lt; n &amp;&amp; arr[Math.min(step, n) - 1] &lt; target) {<br>            System.out.println(&quot;Fetching page starting at index: &quot; + step);<br><br>            prev = step;<br>            step += (int) Math.sqrt(n);<br><br>            if (prev &gt;= n) return -1;<br>        }<br><br>        // Linear scan within the found block<br>        System.out.println(&quot;Scanning within page range...&quot;);<br><br>        while (prev &lt; Math.min(step, n)) {<br>            System.out.println(&quot;Checking index: &quot; + prev);<br><br>            if (arr[prev] == target) {<br>                return prev;<br>            }<br>            prev++;<br>        }<br><br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br>        // Simulated sorted dataset (like API results across pages)<br>        int[] data = {<br>                2, 4, 6, 8, 10,<br>                12, 14, 16, 18, 20,<br>                22, 24, 26, 28, 30,<br>                32, 34, 36, 38, 40<br>        };<br><br>        int target = 26;<br><br>        int result = jumpSearch(data, target);<br><br>        if (result != -1) {<br>            System.out.println(&quot;\nElement found at index: &quot; + result);<br>        } else {<br>            System.out.println(&quot;\nElement not found.&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Fetching page starting at index: 4<br>// Fetching page starting at index: 8<br>// Fetching page starting at index: 12<br>// Scanning within page range...<br>// Checking index: 12<br>// Element found at index: 12</pre><p>This version works well because it keeps access patterns sequential and predictable: a few large jumps to locate the right region, followed by a short local scan. In systems where each “jump” could represent a costly operation (like an API call or data fetch), reducing back-and-forth movement can matter more than theoretical optimal comparisons.</p><h4>2. Searching in database-style storage indexes (SSTables / LSM trees)</h4><p>A very realistic use case appears inside modern database storage engines, especially systems built on log-structured merge trees, where data is stored in sorted blocks on disk.</p><p>Instead of being held in memory, records are written into sorted segments and later merged. Each segment has an ordered index, but accessing arbitrary positions often involves disk reads, which are significantly more expensive than CPU operations.</p><p>In this environment, algorithms such as binary search is not always ideal in practice. Although it reduces comparisons, it repeatedly jumps to different parts of the index, which can trigger multiple disk seeks or cache misses.</p><p>Jump Search fits more naturally here because it moves forward through the index in fixed steps, gradually narrowing the region where the key might exist. This produces a more sequential access pattern, which aligns better with how storage systems are optimized. Once the correct block is identified, a short in-memory scan is enough to locate the exact entry.</p><pre>public class Main {<br><br>    static class Entry {<br>        String key;<br>        int value;<br><br>        Entry(String key, int value) {<br>            this.key = key;<br>            this.value = value;<br>        }<br>    }<br><br>    public static int jumpSearch(Entry[] table, String targetKey) {<br>        int n = table.length;<br>        int step = (int) Math.sqrt(n);<br>        int prev = 0;<br><br>        while (prev &lt; n &amp;&amp; table[Math.min(step, n) - 1].key.compareTo(targetKey) &lt; 0) {<br>            prev = step;<br>            step += (int) Math.sqrt(n);<br><br>            if (prev &gt;= n) return -1;<br>        }<br><br>        while (prev &lt; Math.min(step, n)) {<br>            if (table[prev].key.equals(targetKey)) {<br>                return table[prev].value;<br>            }<br>            prev++;<br>        }<br><br>        return -1;<br>    }<br><br>    public static void main(String[] args) {<br><br>        Entry[] table = {<br>                new Entry(&quot;a01&quot;, 10),<br>                new Entry(&quot;a05&quot;, 20),<br>                new Entry(&quot;a09&quot;, 30),<br>                new Entry(&quot;a13&quot;, 40),<br>                new Entry(&quot;a17&quot;, 50),<br>                new Entry(&quot;a21&quot;, 60),<br>                new Entry(&quot;a25&quot;, 70),<br>                new Entry(&quot;a29&quot;, 80),<br>                new Entry(&quot;a33&quot;, 90),<br>                new Entry(&quot;a37&quot;, 100)<br>        };<br><br>        String target = &quot;a25&quot;;<br><br>        int result = jumpSearch(table, target);<br><br>        System.out.println(result != -1 ? &quot;Value found: &quot; + result : &quot;Key not found.&quot;);<br>    }<br>}<br><br>// Output:<br>// Value found: 70</pre><p>This example shows how Jump Search can feel more natural in systems where data is already structured in sorted segments and access costs are not uniform. Instead of optimizing purely for the number of comparisons, it takes into account how data is actually retrieved — favoring sequential movement over frequent random jumps.</p><p>In practice, this makes it less about competing with binary search in ideal conditions and more about fitting specific system constraints. When data lives on disk or in indexed storage layers, reducing expensive access patterns can matter more than shaving off a few comparisons in memory.</p><h3>Conclusion 📣</h3><p>Jump Search may not be the most efficient algorithm in terms of pure theoretical performance, but that’s not where its value lies. Its strength comes from simplicity, predictability, and how naturally it fits into systems where access patterns matter just as much as computation.</p><p>Across the examples, we saw how Jump Search sits in a practical middle ground between linear and binary search — reducing unnecessary comparisons while avoiding the complexity of more advanced techniques. Whether it’s working with paginated data, structured storage systems, or sorted object collections, the algorithm consistently shows how small design choices (like fixed-step jumps) can align better with real-world constraints than purely optimal strategies.</p><p>Ultimately, Jump Search is a reminder that algorithm choice isn’t just about Big-O notation. It’s about context — how data is stored, how it’s accessed, and what kind of cost actually dominates in practice. In the right situations, a simple and predictable approach can be more effective than a theoretically faster one.</p><p>Happy coding! 😃</p><p>🙏 <strong>Thanks</strong> for reading to the end! If you have any questions, feel free to drop a comment below.</p><p>If you enjoyed this article, follow me on medium or social media — I’d love to connect and follow you back:</p><ul><li><a href="https://x.com/RobinViktorsson">Robin Viktorsson (@RobinViktorsson) / X</a></li><li><a href="https://mastodon.social/@robinviktorsson">Robin Viktorsson (@robinviktorsson@mastodon.social) — Mastodon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=633876051750" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>