Skip to content
codingtube

codingtube

Coding and Programming tutorials

  • javascript
  • React
  • ES6
  • React js
  • coding
  • ffmpeg
  • java
  • programming
  • information
  • coding
  • Privacy Policy
  • Twitter trends
  • Age Calculatore
  • Codingtube Community
  • YouTube Tags Generator
  • About
  • Toggle search form

Bellman Ford in java

Posted on December 1, 2021December 1, 2021 By christo No Comments on Bellman Ford in java

Complete program of Bellman Ford in java

package com.thealgorithms.datastructures.graphs;

import java.util.*;

class BellmanFord  {

    int vertex, edge;
    private Edge edges[];
    private int index = 0;

    BellmanFord(int v, int e) {
        vertex = v;
        edge = e;
        edges = new Edge[e];
    }

    class Edge {

        int u, v;
        int w;

        /**
         * @param u Source Vertex
         * @param v End vertex
         * @param c Weight
         */
        public Edge(int a, int b, int c) {
            u = a;
            v = b;
            w = c;
        }
    }

    /**
     * @param p[] Parent array which shows updates in edges
     * @param i Current vertex under consideration
     */
    void printPath(int p[], int i) {
        if (p[i] == -1) // Found the path back to parent
        {
            return;
        }
        printPath(p, p[i]);
        System.out.print(i + " ");
    }

    public static void main(String args[]) {
        BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables
        obj.go();
    }

    public void
            go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and
    // shows distance to all vertices
    {
        Scanner sc = new Scanner(System.in); // Grab scanner object for user input
        int i, v, e, u, ve, w, j, neg = 0;
        System.out.println("Enter no. of vertices and edges please");
        v = sc.nextInt();
        e = sc.nextInt();
        Edge arr[] = new Edge[e]; // Array of edges
        System.out.println("Input edges");
        for (i = 0; i < e; i++) {
            u = sc.nextInt();
            ve = sc.nextInt();
            w = sc.nextInt();
            arr[i] = new Edge(u, ve, w);
        }
        int dist[]
                = new int[v]; // Distance array for holding the finalized shortest path distance between source
        // and all vertices
        int p[] = new int[v]; // Parent array for holding the paths
        for (i = 0; i < v; i++) {
            dist[i] = Integer.MAX_VALUE; // Initializing distance values
        }
        dist[0] = 0;
        p[0] = -1;
        for (i = 0; i < v - 1; i++) {
            for (j = 0; j < e; j++) {
                if ((int) dist[arr[j].u] != Integer.MAX_VALUE
                        && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
                    dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
                    p[arr[j].v] = arr[j].u;
                }
            }
        }
        // Final cycle for negative checking
        for (j = 0; j < e; j++) {
            if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
                neg = 1;
                System.out.println("Negative cycle");
                break;
            }
        }
        if (neg == 0) // Go ahead and show results of computation
        {
            System.out.println("Distances are: ");
            for (i = 0; i < v; i++) {
                System.out.println(i + " " + dist[i]);
            }
            System.out.println("Path followed:");
            for (i = 0; i < v; i++) {
                System.out.print("0 ");
                printPath(p, i);
                System.out.println();
            }
        }
        sc.close();
    }

    /**
     * @param source Starting vertex
     * @param end Ending vertex
     * @param Edge Array of edges
     */
    public void show(
            int source,
            int end,
            Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should
    // be created by using addEdge() method and passed by calling getEdgeArray() method
    {
        int i, j, v = vertex, e = edge, neg = 0;
        double dist[]
                = new double[v]; // Distance array for holding the finalized shortest path distance between source
        // and all vertices
        int p[] = new int[v]; // Parent array for holding the paths
        for (i = 0; i < v; i++) {
            dist[i] = Integer.MAX_VALUE; // Initializing distance values
        }
        dist[source] = 0;
        p[source] = -1;
        for (i = 0; i < v - 1; i++) {
            for (j = 0; j < e; j++) {
                if ((int) dist[arr[j].u] != Integer.MAX_VALUE
                        && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
                    dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
                    p[arr[j].v] = arr[j].u;
                }
            }
        }
        // Final cycle for negative checking
        for (j = 0; j < e; j++) {
            if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
                neg = 1;
                System.out.println("Negative cycle");
                break;
            }
        }
        if (neg == 0) // Go ahead and show results of computaion
        {
            System.out.println("Distance is: " + dist[end]);
            System.out.println("Path followed:");
            System.out.print(source + " ");
            printPath(p, end);
            System.out.println();
        }
    }

    /**
     * @param x Source Vertex
     * @param y End vertex
     * @param z Weight
     */
    public void addEdge(int x, int y, int z) // Adds unidirectional edge
    {
        edges[index++] = new Edge(x, y, z);
    }

    public Edge[] getEdgeArray() {
        return edges;
    }
}
Algorithm, java Tags:Bellman Ford in java, java

Post navigation

Previous Post: A star graph implementation in java
Next Post: Bipartite graph implementation in java

Related Posts

Leetcode Valid Palindrome String java
How to Reuse Views and Layouts With INCLUDE and MERGE in Android Algorithm
Bogosort in java | permutation sort java
Gnome Sort in java java
How to Create Thread in java ? java
ArrayList in java java

Leave a Reply Cancel reply

You must be logged in to post a comment.

Recent Posts

  • Affiliate Marketing Principles
  • The Basics You Need to Know About Affiliate Marketing
  • Affiliate Marketing Options
  • All About Affiliate Marketing
  • Classification of Database Management Systems
  • Three-Tier and n-Tier Architectures
    for Web Applications
  • Two-Tier Client/Server Architectures for DBMSs
  • Basic Client/Server Architectures in DBMS
  • Centralized DBMSs Architecture in DBMS
  • Tools, Application Environments, and Communications Facilities in DBMS

Categories

  • Affiliate marketing (5)
  • Algorithm (43)
  • amp (3)
  • android (223)
  • Android App (8)
  • Android app review (4)
  • android tutorial (60)
  • Artificial intelligence (61)
  • AWS (3)
  • bitcoin (8)
  • blockchain (1)
  • c (5)
  • c language (105)
  • cloud computing (4)
  • coding (4)
  • coding app (4)
  • complex number (1)
  • Computer Graphics (66)
  • data compression (65)
  • data structure (188)
  • DBMS (44)
  • digital marketing (9)
  • distributed systems (11)
  • ffmpeg (26)
  • game (3)
  • html (6)
  • image processing (35)
  • Inequalities (1)
  • information (4)
  • java (212)
  • java network (1)
  • javascript (9)
  • kotlin (4)
  • leetcode (1)
  • math (21)
  • maven (1)
  • mysql (1)
  • Node.js (8)
  • operating system (109)
  • php (310)
  • Principle Of Mathematical Induction (1)
  • programming (6)
  • Python (4)
  • Python data structure (9)
  • React native (1)
  • React.js (22)
  • Redux (1)
  • seo (4)
  • set (12)
  • trigonometry (6)
  • vue.js (35)
  • XML (3)

sitemap

sitemap of videos

sitemap of webstories

sitemap of website

  • Affiliate marketing
  • Algorithm
  • amp
  • android
  • Android App
  • Android app review
  • android tutorial
  • Artificial intelligence
  • AWS
  • bitcoin
  • blockchain
  • c
  • c language
  • cloud computing
  • coding
  • coding app
  • complex number
  • Computer Graphics
  • data compression
  • data structure
  • DBMS
  • digital marketing
  • distributed systems
  • ffmpeg
  • game
  • html
  • image processing
  • Inequalities
  • information
  • java
  • java network
  • javascript
  • kotlin
  • leetcode
  • math
  • maven
  • mysql
  • Node.js
  • operating system
  • php
  • Principle Of Mathematical Induction
  • programming
  • Python
  • Python data structure
  • React native
  • React.js
  • Redux
  • seo
  • set
  • trigonometry
  • vue.js
  • XML
  • Blog
  • Data compression tutorial - codingpoint
  • How to change mbstring in php 5.6
  • How to diagnose out of memory killed PHP-FPM
  • Introduction to jQuery
  • Privacy
  • Affiliate marketing
  • Algorithm
  • amp
  • android
  • Android App
  • Android app review
  • android tutorial
  • Artificial intelligence
  • AWS
  • bitcoin
  • blockchain
  • c
  • c language
  • cloud computing
  • coding
  • coding app
  • complex number
  • Computer Graphics
  • data compression
  • data structure
  • DBMS
  • digital marketing
  • distributed systems
  • ffmpeg
  • game
  • html
  • image processing
  • Inequalities
  • information
  • java
  • java network
  • javascript
  • kotlin
  • leetcode
  • math
  • maven
  • mysql
  • Node.js
  • operating system
  • php
  • Principle Of Mathematical Induction
  • programming
  • Python
  • Python data structure
  • React native
  • React.js
  • Redux
  • seo
  • set
  • trigonometry
  • vue.js
  • XML
  • Blog
  • Data compression tutorial - codingpoint
  • How to change mbstring in php 5.6
  • How to diagnose out of memory killed PHP-FPM
  • Introduction to jQuery
  • Privacy

© codingtube.tech