• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Find shortest distances between every pair of vertices ( Dynamic Programming Floyd Warshall Algorithm)

February 23, 2018 by Dhaval Dave

Find shortest distances between every pair of vertices in a given edge weighted directed Graph.

Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow . The first line of each test case contains an integer V denoting the size of the adjacency matrix  and in the next line are V*V space separated values of the matrix (graph) .

Output:
For each test case output will be V*V space separated integers where the i-jth integer denote the shortest distance of ith vertex from jth vertex.

Constraints:
1<=T<=20
1<=V<=20
-1000<=graph[][]<=1000

Example:
Input

2
2
0 25 25 0
3
0 1 43 1 0 6 43 6 0

Output
0 25 25 0
0 1 7 1 0 6 7 6 0

Explanation : –

To Find shortest distances between every pair of vertices We first initialize the solution matrix same as the input graph matrix as a first step. Then we update the solution matrix by considering all vertices as an intermediate vertex. The idea is to one by one pick all vertices and update all shortest paths which include the picked vertex as an intermediate vertex in the shortest path. When we pick vertex number k as an intermediate vertex, we already have considered vertices {0, 1, 2, .. k-1} as intermediate vertices. For every pair (i, j) of source and destination vertices respectively, there are two possible cases.
All steps are explained in below images.
1) k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it is.
2) k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as dist[i][k] + dist[k][j].

Code(C++) To Find shortest distances between every pair of vertices : –

#include <stdio.h>
#define ll long long
using namespace std;

int main() {
        ll t;
        cin >> t;
        while (t--) {
            ll m;
            cin >> m;
            ll dist[m][m];
            for (ll i = 0; i < m; i++)
                for (ll j = 0; j > dist[i][j];

                    for (ll k = 0; k < m; k++)
                        for (ll i = 0; i < m; i++)
                            for (ll j = 0; j < m; j++) {
                                if (dist[i][k] + dist[k][j] < dist[i][j])
                                    dist[i][j] = dist[i][k] + dist[k][j];
                            }

                    for (ll i = 0; i < m; i++)
                        for (ll j = 0; j < m; j++)
                            cout << dist[i][j] << " "; cout << "\n";
                }
            return 0;
        }

Similar Articles

Filed Under: Amazon Interview Question, Graph, Microsoft Interview Questions Tagged With: Dynamic Programming, Graph

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Introduction To Number Theory ( Part 1 )

K’th Largest Element in BST when modification to BST is not allowed

Given a float number convert it into the string WITHOUT using any inbuilt Function

SAP Hiring Off-Campus General Aptitude

Sort an array according to the order defined by another array

DFS (Depth First Search)

Find an index i such that Arr [i] = i in array of n distinct integers sorted in ascending order.

C++ OOPs Part1

Find min element in Sorted Rotated Array (With Duplicates)

Level order traversal in Spiral form

Binary Tree in Java

Cisco Hiring Event 21st – 22nd Feb 2015

Handle duplicates in Binary Search Tree

Find next greater number with same set of digits

1014 Practice Question of New GRE – Princeton

Print vertical sum of all the axis in the given binary tree

Get K Max and Delete K Max in stream of incoming integers

Mirror of Tree

Advanced SQL Injection

Find if two rectangles overlap

Skiing on Mountains Matrix

Practo Hiring Experience

Check a String is SUBSEQUENCE of another String Find Minimum length for that ( DNA Matching )

Microsoft BING Interview Experience

Rectangular chocolate bar Create at least one piece which consists of exactly nTiles tiles

Maximum sum contiguous subarray of an Array

BlueStone E-commerce Interview Experience

Find position of the only set bit

Count Possible Decodings of a given Digit Sequence

robot standing at first cell of an M*N matrix. It can move only in two directions, right and down. In how many ways, it can reach to the last cell i.e. (M, N) Code it

Copyright © 2025 · Genesis Framework · WordPress · Log in