-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph2.java
More file actions
124 lines (104 loc) · 2.66 KB
/
Graph2.java
File metadata and controls
124 lines (104 loc) · 2.66 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package graph;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
/*
class Neighbor {
public int vertexNum;
public Neighbor next;
public Neighbor(int vnum, Neighbor nbr) {
this.vertexNum = vnum;
next = nbr;
}
}
class Vertex {
String name;
Neighbor adjList;
Vertex(String name, Neighbor neighbors) {
this.name = name;
this.adjList = neighbors;
}
}
*/
/**
* @author Sesh Venugopal. May 31, 2013.
*/
public class Graph2 {
Vertex[] adjLists;
public Graph2(String file) throws FileNotFoundException {
Scanner sc = new Scanner(new File(file));
String graphType = sc.next();
boolean undirected=true;
if (graphType.equals("directed")) {
undirected=false;
}
adjLists = new Vertex[sc.nextInt()];
// read vertices
for (int v=0; v < adjLists.length; v++) {
adjLists[v] = new Vertex(sc.next(), null);
}
// read edges
while (sc.hasNext()) {
// read vertex names and translate to vertex numbers
int v1 = indexForName(sc.next());
int v2 = indexForName(sc.next());
// add v2 to front of v1's adjacency list and
// add v1 to front of v2's adjacency list
adjLists[v1].adjList = new Neighbor(v2, adjLists[v1].adjList);
if (undirected) {
adjLists[v2].adjList = new Neighbor(v1, adjLists[v2].adjList);
}
}
}
int indexForName(String name) {
for (int v=0; v < adjLists.length; v++) {
if (adjLists[v].name.equals(name)) {
return v;
}
}
return -1;
}
public void print() {
System.out.println();
for (int v=0; v < adjLists.length; v++) {
System.out.print(adjLists[v].name);
for (Neighbor nbr=adjLists[v].adjList; nbr != null;nbr=nbr.next) {
System.out.print(" --> " + adjLists[nbr.vertexNum].name);
}
System.out.println("\n");
}
}
/**
* @param args
*/
public static void main(String[] args)
throws IOException {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter graph input file name: ");
String file = sc.nextLine();
Graph2 graph = new Graph2(file);
// graph.print();
}
}
// undirected
//10
//Sara
//Sam
//Sean
//Ajay
//Mira
//Jane
//Maria
//Rahul
//Sapna
//Rohit
//Sara Sam
//Sara Ajay
//Sam Sean
//Sam Mira
//Mira Jane
//Jane Maria
//Rahul Sapna
//Sapna Rohit