-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
108 lines (91 loc) · 3.18 KB
/
Graph.java
File metadata and controls
108 lines (91 loc) · 3.18 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
import java.util.*;
public class Graph {
private Map<String, List<String>> adjList;
public Graph() {
adjList = new HashMap<>();
}
public void addLocation(String location) {
adjList.putIfAbsent(location, new ArrayList<>());
}
public void removeLocation(String location) {
// Remove the vertex itself
adjList.remove(location);
// Remove all edges pointing to this vertex
for (List<String> connections : adjList.values()) {
connections.remove(location);
}
}
public void addRoad(String from, String to) {
if (!adjList.containsKey(from) || !adjList.containsKey(to)) {
System.out.println("Error: One or both locations not found.");
return;
}
// Add road (undirected)
if (!adjList.get(from).contains(to)) {
adjList.get(from).add(to);
}
if (!adjList.get(to).contains(from)) {
adjList.get(to).add(from);
}
}
public void removeRoad(String from, String to) {
if (adjList.containsKey(from) && adjList.containsKey(to)) {
adjList.get(from).remove(to);
adjList.get(to).remove(from);
} else {
System.out.println("Error: One or both locations not found.");
}
}
public void displayConnections() {
if (adjList.isEmpty()) {
System.out.println("No locations or connections to display.");
return;
}
for (String loc : adjList.keySet()) {
System.out.println(loc + " -> " + adjList.get(loc));
}
}
/**
* REQUIREMENT 4: Uses a Queue for a traversal (BFS) to find a path.
*/
public void findPath(String start, String end) {
if (!adjList.containsKey(start) || !adjList.containsKey(end)) {
System.out.println("Error: One or both locations do not exist.");
return;
}
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
Map<String, String> parentMap = new HashMap<>(); // To reconstruct path
queue.add(start);
visited.add(start);
parentMap.put(start, null);
boolean found = false;
while (!queue.isEmpty()) {
String current = queue.poll(); // Dequeue
if (current.equals(end)) {
found = true;
break;
}
for (String neighbor : adjList.get(current)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
parentMap.put(neighbor, current); // Track the path
queue.add(neighbor); // Enqueue
}
}
}
if (found) {
// Reconstruct path
List<String> path = new ArrayList<>();
String current = end;
while (current != null) {
path.add(current);
current = parentMap.get(current);
}
Collections.reverse(path);
System.out.println("Path found: " + path);
} else {
System.out.println("No path found between " + start + " and " + end);
}
}
}