Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions lesson7/src/Graph.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import java.util.*;

public class Graph {
private class Vertex {
public char label;
Expand All @@ -18,18 +20,27 @@ public String toString() {
private Vertex[] vertices;
private int[][] adjMatrix;
private int size;
private TreeMap<Character, Integer> map;
private ArrayList<Integer> path;

public Graph(int size) {
this.MAX_VERTICES = size;
vertices = new Vertex[MAX_VERTICES];
adjMatrix = new int[MAX_VERTICES][MAX_VERTICES];
map = new TreeMap<>();
path = new ArrayList<>();
}

public void addVertex(char label) {
map.put(label, size);
vertices[size++] = new Vertex(label);
}

public void addEdge(int start, int end) {
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
public void addEdge(char label, char label2) {
int v = map.get(label);
int v2 = map.get(label2);
adjMatrix[v][v2] = 1;
adjMatrix[v2][v] = 1;
}

public void showVertex(int vertex) {
Expand Down Expand Up @@ -69,20 +80,46 @@ public void depthTravers() {
resetFlags();
}

public void widthTravers(){
public void widthTraverseSearch(char label){
int v = map.get(label);

Queue queue = new Queue(MAX_VERTICES);
vertices[0].wasVisited = true;
showVertex(0);
queue.insert(0);
while (!queue.isEmpty()){
int vCurr = queue.remove();
if (vCurr == v) {
path.add(vCurr);
break;
}
int vNext;

while ((vNext = getUnvisitedVertex(vCurr)) != -1){
vertices[vNext].wasVisited = true;
showVertex(vNext);
if (vNext == v) {
path.add(vNext);

map.entrySet().forEach(entry -> {
if (entry.getValue() == vCurr) {
resetFlags();
widthTraverseSearch(entry.getKey());
}
});
return;
}
queue.insert(vNext);

}
}
resetFlags();

for (int i = path.size() - 1; i >= 0 ; i--) {
int w = i;
map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), path.get(w)))
.findFirst()
.ifPresent(entry -> System.out.printf("%s ", entry.getKey()));
}
}
}
29 changes: 29 additions & 0 deletions lesson7/src/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
public class Main {
public static void main(String[] args) {
Graph graph = new Graph(10);
graph.addVertex('a');
graph.addVertex('b');
graph.addVertex('c');
graph.addVertex('d');
graph.addVertex('e');
graph.addVertex('f');
graph.addVertex('g');
graph.addVertex('h');
graph.addVertex('i');
graph.addVertex('j');

graph.addEdge('a', 'b');
graph.addEdge('a', 'c');
graph.addEdge('b', 'd');
graph.addEdge('b', 'e');
graph.addEdge('d', 'a');
graph.addEdge('c', 'f');
graph.addEdge('f', 'g');
graph.addEdge('d', 'h');
graph.addEdge('g', 'i');
graph.addEdge('g', 'j');
graph.addEdge('h', 'j');

graph.widthTraverseSearch('j');
}
}