• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Dijkstra: Shortest Reach 2 – HackerRank Solution

Dijkstra: Shortest Reach 2 - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 26, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Dijkstra: Shortest Reach 2 – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ replace HackerRank Solution
  • Java rep HackerRank Solution
  • Python 3 Dijkstra: Shortest Reach 2 HackerRank Solution
  • Python 2 Dijkstra: Shortest Reach 2 HackerRank Solution
  • C Dijkstra: Shortest Reach 2 HackerRank Solution
    • Leave a comment below
      • Related posts:

Dijkstra: Shortest Reach 2 – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ replace HackerRank Solution


Copy Code Copied Use a different Browser

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class node{
    public:
    int val;
    int dis;
    int vis ;
    int add;
   long int edist;
    node *next;
    node(int n, node *ptr, long int edist){
        val = n;
        this->edist = edist; 
        dis = -1;
        vis = 0;
        add = 0;
        next  = ptr;
    }
};

void breadth(node **adj,node *queue,node *last,long int *dist){
     if(queue!=NULL){
           node *temp = adj[queue->val];
           while(temp!=NULL){
               if(dist[temp->val]==-1 || dist[temp->val] > dist[queue->val]+temp->edist){
                   dist[temp->val] = dist[queue->val] + temp->edist;
                   node *ptr = new node(temp->val, NULL, 0);
                   last->next = ptr;
                   last = ptr;
               }
               temp = temp->next;
           }
         queue = queue->next;
    /*     
         cout<<"queue\n";
         temp = queue;
         while(temp !=NULL){
             cout<<temp->val+1<<" ";
             temp = temp->next;
         }
         cout<<endl;
      */   
         breadth(adj,queue,last,dist);
     }
 }



int main() {
  long int t;
    cin>>t;
    while(t--){
        long int n,m;
        cin>>n;
        node *adj[n];
        for(long int i=0;i<n;i++){
            adj[i] = NULL;
        }
        cin>>m;
        for(long int i=0;i<m;i++){
            long int x, y, z;
            cin>>x>>y>>z;
            node *ptr = new node(x-1,adj[y-1],z);
            adj[y-1] = ptr;
           ptr = new node(y-1,adj[x-1],z);
            adj[x-1] = ptr;
        }
        /* cout<<"printing queue"<<endl;
        for(long int i=0;i<n;i++){
            node *ptr = adj[i];
            while(ptr!=NULL){
                cout<<ptr->val+1<<" + " <<ptr->edist<<" ";
                ptr = ptr->next;
            }
            cout<<endl;
        }
        */
        
        long int s;
        cin>>s;
        s = s-1;
       
        
        
        node *queue, *last;
        node *ptr  = new node(s,NULL,0);
        long int dist[n];
        for(long int i=0;i<=n;i++)
            dist[i] = -1;
        dist[s] = 0;
        queue = ptr;
        last = ptr;
        breadth(adj,queue,last, dist);
        for(long int i=0;i<n;i++){
            if(i!=s){
                cout<<dist[i]<<" ";
            }
        }
        cout<<endl;
    }
    
    return 0;
}

Java rep HackerRank Solution


Copy Code Copied Use a different Browser

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Node implements Comparable<Node>{
    int val, cost;
    Node(int val, int cost){
        this.val = val; this.cost = cost;
    }
    
    public int compareTo(Node x){
        return Integer.compare(this.cost, x.cost);
    }
}

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while(t-- > 0){
            int n = sc.nextInt(), m = sc.nextInt();
            ArrayList<ArrayList<Node>> adj = new ArrayList<ArrayList<Node>>(n+1);
            for(int i=0; i<n+1; i++)adj.add(new ArrayList<Node>(n+1));
        
            while(m-- > 0){
                int x = sc.nextInt(), y = sc.nextInt(), cost = sc.nextInt();
                adj.get(x).add(new Node(y, cost));
                adj.get(y).add(new Node(x, cost));
            }
            int s = sc.nextInt();
            djikstra(s, adj, n);
        }
    }
    
    static void djikstra(int s, ArrayList<ArrayList<Node>> adj, int n){
        int[] dist = new int[n+1];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[s] = 0;
        PriorityQueue<Node> pq = new PriorityQueue<Node>();
        pq.add(new Node(s, 0));
        while(pq.size() > 0){
            Node curr = pq.peek(); pq.remove();
            int currN = curr.val;
            Iterator<Node> it = adj.get(currN).iterator();
            while(it.hasNext()){
                Node temp = it.next();
                if(dist[temp.val] > dist[currN] + temp.cost){
                    pq.add(new Node(temp.val, dist[currN]+temp.cost));
                    dist[temp.val] = dist[currN] + temp.cost;
                }
            }
        }
        
        for(int i=1; i<dist.length; i++){
            if(i!=s){
                System.out.print(((dist[i] == Integer.MAX_VALUE)?-1:dist[i]) + " ");
            }
        }
        System.out.println();
    }
}

 



Python 3 Dijkstra: Shortest Reach 2 HackerRank Solution


Copy Code Copied Use a different Browser

import heapq

def find(V,N,S):
    dist=[-1 for x in range(N)]
    visited=[False for x in range(N)]
    Q=[(0,S)] #use a priority queue
    dist[S]=0
    while Q:
        mindist,minv=heapq.heappop(Q)
        if not visited[minv]:
            for x in V[minv]:
                if dist[x] == -1: dist[x]=mindist+V[minv][x]
                else: dist[x]=min(dist[x],mindist+V[minv][x])
                heapq.heappush(Q,(dist[x],x))
            visited[minv]=True
    del dist[S]
    for x in dist: print(x,end=' ')
    print()

def update(V,X,Y,R):
    if Y not in V[X]: V[X][Y]=R
    else: V[X][Y]=min(V[X][Y],R)

T=int(input())
for _ in range(T):
    N,M=(int(x) for x in input().split())
    V=[dict() for x in range(N)]
    for i in range(M):
        X,Y,R=(int(x) for x in input().split())
        X,Y=X-1,Y-1
        update(V,X,Y,R)
        update(V,Y,X,R)
    find(V,N,int(input())-1)



Python 2 Dijkstra: Shortest Reach 2 HackerRank Solution


Copy Code Copied Use a different Browser

def killdoubles(l):
    i=0
    a=l[i]
    ll=[a]
    while i<len(l):
        if a!=l[i]:
            a=l[i]
            ll.append(a)
        i+=1
    return ll

def argminnonmarque(l,m):
    mini=min([l[i] for i in range(len(l)) if not(m[i])])
    for i in range(len(l)):
        if ((l[i]==mini) & (not(m[i]))):
            break
    return i
def subs(a,l):
    i=0
    dont=False
    while i<len(l):
        if l[i][0]==a[0]:
            if l[i][1]>a[1]:
                break
            dont=True
        i+=1
    ll=[list(k) for k in l]
    if i<len(l):
        ll[i]=a
    elif not(dont):
        ll.append(a)
    return ll
def solve(n,m,r,s):
    G=[[] for _ in range(n+1)]
    for [i,j,w] in r:
        G[i]=subs([j,w],G[i])
        G[j]=subs([i,w],G[j])
        
    infinity=1+sum([r[i][2] for i in range(m)])
    
    for debut in [s]:
        marque=[False for _ in range(n+1)]
        labels=[infinity for _ in range(n+1)]
        labels[debut]=0
        while marque!=[True for _ in range(n+1)]:
            a=argminnonmarque(labels,marque)
            marque[a]=True
            for [b,w] in G[a]:
                if not(marque[b]):
                    labels[b]=min(labels[b],labels[a]+w)
        for i in range(n+1):
            if labels[i]==infinity:
                labels[i]=-1
    st=""
    for i in (labels[1:s]+labels[s+1:]):
        st+=str(i)+" "
    return st


T=int(raw_input())
for _ in range(T):
    [n,m]=map(int,raw_input().strip().split())
    r=[]
    for _ in range(m):
        r.append(map(int,raw_input().strip().split()))
    s=int(raw_input())
    print(solve(n,m,r,s))



C Dijkstra: Shortest Reach 2 HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define FROM 0
#define TO 1
#define LENGTH 2
#define DISTANCE 0
#define STATUS 1
#define SPENT 0
#define PENDING 1

int edge[3000*(3000-1)/2+1][3];	// [edge][FROM/TO/LENGTH]

int main() {
    
	int cases, nodes, edges, origin, active, neighbor, i;
	unsigned int mindist;
	int node[3000+1][2];		// [node][DISTANCE/STATUS]
	
	scanf("%d", &cases);
	
	while(cases--){
		
		scanf("%d %d", &nodes, &edges);
		
		for(i=1; i <= edges; i++){
			scanf("%d %d %d", &edge[i][FROM], &edge[i][TO], &edge[i][LENGTH]);
		}
	
		for(i=1; i <= nodes; i++){
			node[i][DISTANCE] = -1;      //infinity
			node[i][STATUS] = PENDING;
		}
		
		scanf("%d", &origin);
		active = origin;
		node[origin][DISTANCE] = 0;
        
		while(active){
				
			for(i=1; i<=edges; i++){
				
				if(edge[i][FROM]==active){
					neighbor = edge[i][TO];
				}
				else if(edge[i][TO]==active){  //test graph is actually undirected
					neighbor = edge[i][FROM];
				}
				else continue;

				if(node[neighbor][DISTANCE] == -1){
					node[neighbor][DISTANCE] = node[active][DISTANCE] + edge[i][LENGTH];
				}
				else if( node[neighbor][DISTANCE] > node[active][DISTANCE] + edge[i][LENGTH] ){
					node[neighbor][DISTANCE] = node[active][DISTANCE] + edge[i][LENGTH];
				}

			}

			node[active][STATUS] = SPENT;
			active = 0;

			mindist = -1; //unsigned
			for(i=1; i <= nodes; i++){ //activate closest unchecked node
				if( node[i][STATUS] == PENDING && node[i][DISTANCE] < mindist ){
					mindist = node[i][DISTANCE];
					active = i;
				}
			}
	
		}
	
		for(i=1; i<=nodes; i++){
			if(i!=origin)printf("%i ", node[i][DISTANCE]);
		}
	
		printf("\n");
	}
    
    return 0;
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionTask Scheduling – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMerge two sorted linked lists – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionRecursive Digit Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLego Blocks – HackerRank Solution
Tags: Cc++14Dijkstra: Shortest Reach 2full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Toll Cost Digits - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Real Estate Broker - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionTask Scheduling – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMerge two sorted linked lists – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionRecursive Digit Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLego Blocks – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Weather Observation Station 9 EasySQL (Basic) – SQL – HackerRank Solution

May 30, 2022
0
Leetcode All Problems Solutions
Code Solutions

4Sum – LeetCode Solution

September 2, 2022
131
Queen of the South Season 6 Release date ,Countdown , Cast, Story, Overview, Trailer
Entertainment

Queen of the South Season 6 Release date

May 8, 2022
2
Biography

Becky Lynch Net Worth, Age, Height , Achivements and more

September 8, 2022
0

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?