-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.java
96 lines (72 loc) · 2.3 KB
/
graph.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com;
public class Solution{
static class Graph {
int vertex;
int[][] adj;
public Graph(int V) {
this.vertex=V;
adj=new int[V][V];
}
public void AddEdge(int u, int v, int w) {
adj[u][v]=w;
}
public void printgraph() {
for(int i=0; i<vertex; i++) {
for(int j=0; j<vertex; j++) {
if(adj[i][j]!=0) {
System.out.println("Vertex - " + i + " is connected to " + j + " with weight " + adj[i][j]);
}
}
}
}
public void print(int[] arr, int source) {
for(int k=0; k<arr.length; k++) {
System.out.println("Source" + " " + source + " to" + " " + k + " is " + arr[k]);
}
}
int find(boolean[] visit, int[] key) {
int min=Integer.MAX_VALUE;
int val=-1;
for(int i=1; i<vertex; i++) {
if(!visit[i] && min>=key[i]) {
min=key[i];
val=i;
}
}
return val;
}
public void get(int s) {
boolean[] visited= new boolean[vertex];
int[] dist = new int[vertex];
for(int i=1; i<vertex; i++) {
dist[i]=Integer.MAX_VALUE;
// visited[i]=false;
}
dist[s]=0;
for(int i=1; i<vertex; i++) {
int t = find(visited, dist);
visited[t] = true;
for (int l = 1; l <vertex; l++) {
if (adj[t][l] > 0) {
if (!visited[l] && adj[t][l] != Integer.MAX_VALUE) {
int num= adj[t][l] +dist[t];
if(num<dist[l]) {
dist[l]=num;
}
}
}
}
}
print(dist,s);
}
}
public static void main(String[] args) throws Exception {
Graph graph = new Graph(5);
graph.AddEdge(0,2,3);
graph.AddEdge(1,2,6);
graph.AddEdge(2,3,5);
graph.AddEdge(4,2,1);
graph.AddEdge(3,4,4);
graph.printgraph();
}
}