What is wrong in my code?

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for (int i = 0; i < t; i++) {
graph g = new graph();
int nodes = scn.nextInt();
int edges = scn.nextInt();
for (int i1 = 1; i1 <= nodes; i1++) {
String s = “”;
s += i1;
g.addVertex(s);
s = “”;
}
for (int j = 0; j < edges; j++) {
String v1 = scn.next();

			String v2 = scn.next();

			int cost = scn.nextInt();

			g.addEdges(v1, v2, cost);

		}
		String src = scn.next();
		HashMap<String, Integer> ans = g.Dijkstra(src);

		for (String vtx : g.vtcs.keySet()) {
			if (vtx.equals(src)) {
				continue;
			}
			System.out.print(ans.get(vtx) + " ");
		}

	}

}

}
class graph {
public class HeapGeneric<T extends Comparable> {

	ArrayList<T> data = new ArrayList<>();

	HashMap<T, Integer> map = new HashMap<>();

	public void add(T item) {

		data.add(item);
		map.put(item, this.data.size() - 1);
		upheapify(data.size() - 1);
	}

	private void upheapify(int ci) {

		int pi = (ci - 1) / 2;

		if (isLarger(data.get(ci), data.get(pi)) > 0) {
			swap(pi, ci);
			upheapify(pi);
		}
	}

	private void swap(int i, int j) {

		T ith = data.get(i);
		T jth = data.get(j);

		data.set(i, jth);
		data.set(j, ith);

		map.put(ith, j);
		map.put(jth, i);

	}

	public void display() {
		System.out.println(data);
	}

	public int size() {
		return this.data.size();
	}

	public boolean isEmpty() {
		return this.size() == 0;
	}

	public T remove() {

		swap(0, this.data.size() - 1);
		T rv = this.data.remove(this.data.size() - 1);
		downheapify(0);

		map.remove(rv);
		return rv;
	}

	private void downheapify(int pi) {

		int lci = 2 * pi + 1;
		int rci = 2 * pi + 2;

		int mini = pi;

		if (lci < this.data.size() && isLarger(data.get(lci), data.get(mini)) > 0) {
			mini = lci;
		}

		if (rci < this.data.size() && isLarger(data.get(rci), data.get(mini)) > 0) {
			mini = rci;
		}

		if (mini != pi) {
			swap(mini, pi);
			downheapify(mini);
		}

	}

	public T get() {
		return this.data.get(0);
	}

	// if t is having higher priority then return +ve value
	public int isLarger(T t, T o) {
		return t.compareTo(o);
	}

	public void updatePriority(T pair) {

		int index = map.get(pair);

		upheapify(index);

	}

}

private class vertex {
	HashMap<String, Integer> nbrs = new HashMap<>();

}

HashMap<String, vertex> vtcs;

public graph() {
	vtcs = new HashMap<>();
}

public void addVertex(String vname) {
	if (vtcs.containsKey(vname)) {
		return;
	}
	vertex vtx = new vertex();
	vtcs.put(vname, vtx);
}

public void addEdges(String v1, String v2, int cost) {
	vertex vtx1 = vtcs.get(v1);
	vertex vtx2 = vtcs.get(v2);
	if (vtx1 == null || vtx2 == null || vtx1.nbrs.containsKey(v2)) {
		return;
	}
	vtx1.nbrs.put(v2, cost);
	vtx2.nbrs.put(v1, cost);
}

private class DijkstraPair implements Comparable<DijkstraPair> {
	String vname;
	String psf;
	int cost;

	@Override
	public int compareTo(DijkstraPair o) {
		return o.cost - this.cost;
	}

}

public HashMap<String, Integer> Dijkstra(String src) {

	HashMap<String, Integer> ans = new HashMap<>();
	HashMap<String, DijkstraPair> map = new HashMap<>();

	HeapGeneric<DijkstraPair> heap = new HeapGeneric<>();

	// make a pair and put in heap and map
	for (String key : vtcs.keySet()) {

		DijkstraPair np = new DijkstraPair();
		np.vname = key;
		np.psf = "";
		np.cost = Integer.MAX_VALUE;
		if (key.equals(src)) {
			np.cost = 0;
			np.psf = key;
		}
		heap.add(np);
		map.put(key, np);
	}

	// till the heap is not empty keep on removing the pairs
	while (!heap.isEmpty()) {

		// remove a pair
		DijkstraPair rp = heap.remove();
		map.remove(rp.vname);

		// add to mst
		ans.put(rp.vname, rp.cost);

		// nbrs
		for (String nbr : vtcs.get(rp.vname).nbrs.keySet()) {

			// work for nbrs which are in heap
			if (map.containsKey(nbr)) {

				// get the oc and nc
				int oc = map.get(nbr).cost;
				int nc = rp.cost + vtcs.get(rp.vname).nbrs.get(nbr);

				// update the pair only when nc < oc
				if (nc < oc) {

					DijkstraPair gp = map.get(nbr);
					gp.psf = rp.psf + nbr;
					gp.cost = nc;

					heap.updatePriority(gp);
				}
			}

		}

	}

	return ans;

}

}

Your implementation of Dijkstra Algo is wrong. In Dijkstra algorithm , you pick the node with the least distance and then work with its neighbour and proceed this way till all nodes are visited.
In your code, though you do mark the distance of source node as 0, your loop begins with 1 and goes till n
You visit each node in increasing order of their node values. The graph may not always be connected that way as in the testcase above. It may even be not connected at all. Implementing a simple loop as such will not work. Just use dijkstra algo on graph, either by lists or by adjacency matrix. By using hashmaps you are over complicating. This is a greedy algorithm. Make the according changes in your code.
refer to this


please mark your doubt as resolved and rate as well :slight_smile:

package graghproblems; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class dijkstra1 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); for (int i = 0; i < t; i++) { int V = scn.nextInt(); int graph[][]=new int[V][V]; int edges = scn.nextInt(); for(int i1=0;i<V;i++) { for(int j1=0;j1<V;j1++) { graph[i1][j1]=0; } } for (int j = 1; j <= edges; j++) { int v1 = scn.nextInt(); int v2 = scn.nextInt(); int cost = scn.nextInt(); graph[v1-1][v2-1]=cost; } int src = scn.nextInt(); dijkstra( graph, src-1, V); } } static int minDistance(int dist[], Boolean sptSet[], int V) { // Initialize min value int min = Integer.MAX_VALUE, min_index = -1; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) { min = dist[v]; min_index = v; } return min_index; } static // A utility function to print the constructed distance array void printSolution(int dist[], int V) { System.out.println(“Vertex Distance from Source”); for (int i = 0; i < V; i++) System.out.println(i + " tt " + dist[i]); } // Funtion that implements Dijkstra’s single source shortest path // algorithm for a graph represented using adjacency matrix // representation static void dijkstra(int graph[][] , int src, int V) { int dist[] = new int[V]; // The output array. dist[i] will hold // the shortest distance from src to i // sptSet[i] will true if vertex i is included in shortest // path tree or shortest distance from src to i is finalized Boolean sptSet[] = new Boolean[V]; // Initialize all distances as INFINITE and stpSet[] as false for (int i = 0; i < V; i++) { dist[i] = Integer.MAX_VALUE; sptSet[i] = false; } // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of vertices // not yet processed. u is always equal to src in first // iteration. int u = minDistance(dist, sptSet, V); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the // picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, there is an // edge from u to v, and total weight of path from src to // v through u is smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist, V); } }

i am getting error in above code plz check!

please share your code after saving it on ide.codingblocks.com

Here is my code. Find it at Coding Blocks IDE.

i am not able to share the code

https://ide.codingblocks.com/s/369675

plz see the code i have shared the link

For unreachable nodes, print -1.
Consider a testcase like
1
4 2
1 2 24
1 4 20
1

The expected output is
24 -1 20

change your print function

i have donr the changes but it is not submitting

its showing wrong answer

You can use the below test case to debug your code.

Test case:
1
20 54
1 7 45
2 14 15
3 7 29
4 1 48
5 1 66
6 7 17
7 14 15
8 14 43
9 1 27
10 1 33
11 14 64
12 14 27
13 7 66
14 7 54
15 14 56
16 7 21
17 1 20
18 1 34
19 7 52
20 14 14
9 14 9
15 1 39
12 1 24
9 1 16
1 2 33
18 1 46
9 1 28
15 14 3
12 1 27
1 2 5
15 1 34
1 2 28
9 7 16
3 7 23
9 7 21
9 14 19
3 1 20
3 1 5
12 14 19
3 14 2
12 1 46
3 14 5
9 14 44
6 14 26
9 14 16
9 14 34
6 7 42
3 14 27
1 7 9
1 7 41
15 14 19
12 7 13
3 7 10
1 7 2
17

Correct output: 20 25 25 68 86 39 22 70 36 53 91 35 88 27 30 43 54 74 41