Repository navigation
Expand file tree
/
Copy pathIsenbaevNumber1837.java
More file actions
103 lines (85 loc) · 3.01 KB
/
Copy pathIsenbaevNumber1837.java
File metadata and controls
103 lines (85 loc) · 3.01 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
package timus;
import java.util.*;
/**
* Created by sherxon on 2016-11-22.
*/
public class IsenbaevNumber1837 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
IGraph graph= new IGraph();
int n=Integer.parseInt(in.nextLine());
for (int i = 0; i < n; i++) {
String[] s=in.nextLine().split(" ");
graph.addVertex(s[0]);
graph.addVertex(s[1]);
graph.addVertex(s[2]);
graph.addEdge(s[0], s[1]);
graph.addEdge(s[1], s[2]);
graph.addEdge(s[0], s[2]);
}
if(n>0 && graph.vertices.get("Isenbaev")!=null){
graph.bfs(graph.vertices.get("Isenbaev"), new LinkedList<>());
}
graph.print();
}
public static class IGraph{
Map<IVertex, HashSet<IVertex>> map= new HashMap<>();
Map<String, IVertex> vertices= new HashMap<>();
public void addVertex(String v){
vertices.putIfAbsent(v, new IVertex(v));
map.putIfAbsent(vertices.get(v), new HashSet<>());
}
public void addVertex(IVertex v){
map.putIfAbsent(v, new HashSet<>());
}
public void addEdge(String v1, String v2){
map.get(vertices.get(v1)).add(vertices.get(v2));
map.get(vertices.get(v2)).add(vertices.get(v1));
}
public void bfs(IVertex vertex, Queue<IVertex> queue){
vertex.visited=true;
queue.add(vertex);
while (!queue.isEmpty()){
IVertex current=queue.remove();
for (IVertex iVertex : map.get(current)) {
if(!iVertex.visited){
iVertex.visited=true;
iVertex.num=current.num+1;
queue.add(iVertex);
}
}
}
}
public void print() {
List<IVertex> list= new ArrayList<>(map.keySet());
Collections.sort(list, (a, b) -> a.elem.compareTo(b.elem));
for (IVertex vertex : list) {
if(vertex.num == 0 && !"Isenbaev".equals(vertex.elem))
System.out.println(vertex.elem + " undefined");
else
System.out.println(vertex.elem + " " + vertex.num);
}
}
private static class IVertex{
private String elem;
private int num;
private boolean visited;
public IVertex(String elem) {
this.elem = elem;
}
public IVertex() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IVertex vertex = (IVertex) o;
return elem.equals(vertex.elem);
}
@Override
public int hashCode() {
return elem.hashCode();
}
}
}
}