-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathGraph.java
More file actions
59 lines (47 loc) · 1.56 KB
/
Graph.java
File metadata and controls
59 lines (47 loc) · 1.56 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
package org.example;
import java.util.*;
public class Graph {
private Map<String, List<String>> adjList;
public Graph() {
adjList = new HashMap<>();
}
public void addVertex(String vertex) {
adjList.putIfAbsent(vertex, new ArrayList<>());
}
public void addEdges(String vertex, List<String> listOfVertex) {
adjList.putIfAbsent(vertex, new ArrayList<>());
adjList.get(vertex).addAll(listOfVertex);
//adjList.get(vertex2).add(vertex1); //Para grafos não direcionados
}
public Map<String, List<String>> getAdjList() {
return adjList;
}
public void printGraph() {
for (String vertex : adjList.keySet()) {
System.out.print(vertex + " -> ");
for (String neighbor : adjList.get(vertex)) {
System.out.print(neighbor + " ");
}
System.out.println();
}
}
public void breathFirstSearch(String initialVertex) {
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
visited.add(initialVertex);
queue.add(initialVertex);
while(!queue.isEmpty()) {
String vertex = queue.poll();
if(isMangoSeller(vertex)) {
System.out.println("Found it: " + vertex);
return;
} else {
queue.addAll(adjList.get(vertex));
}
}
System.out.println("Didnt find it.");
}
public boolean isMangoSeller(String vertex) {
return vertex.endsWith("m");
}
}