LeetCode - Algorithms - 815. Bus Routes

Hard problem. Accepted after four submissions. Done by myself.

Problem

815. Bus Routes

Java

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
class Solution {
public boolean routesIntersect(int[] route1, int[] route2) {
boolean r = false;
Set<Integer> tmpSet = new HashSet<Integer>();
for(int i=0; i<route1.length; i++)
tmpSet.add(route1[i]);
for(int i=0; i<route2.length; i++) {
if (tmpSet.contains(route2[i])) {
r = true;
break;
}
}
return r;
}

public boolean inArray(int[] a, int x) {
boolean b = false;
for(int i=0; i<a.length; i++) {
if (x==a[i]) {
b = true;
break;
}
}
return b;
}

public int numBusesToDestination(int[][] routes, int S, int T) {
if (S==T) return 0;
int minDist = Integer.MAX_VALUE;

int h = routes.length;

List<Integer> list_S = new ArrayList<Integer>();
for (int i = 0; i < h; i++) {
for (int j = 0; j < routes[i].length; j++) {
if (routes[i][j]==S) {
list_S.add(i);
}
}
}

Map<Integer, List<Integer>> reachableRouteMap = new HashMap<Integer, List<Integer>>();
for(int i=0; i<h; i++) {
List<Integer> list = new ArrayList<Integer>();
for(int j=0; j<h; j++) {
if (j!=i && routesIntersect(routes[i],routes[j])) {
list.add(j);
}
}
reachableRouteMap.put(i,list);
}

boolean[] visited = new boolean[h];
for (int i = 0; i < h; i++) {
visited[i] = false;
}

Queue<Node> q = new LinkedList<>();
for(Integer i : list_S) {
Node s = new Node(i, 1);
q.add(s);
}

while (!q.isEmpty()) {
Node curr = q.poll();
visited[curr.route] = true;
if (inArray(routes[curr.route], T)) {
return curr.dist;
}
List<Integer> list = reachableRouteMap.get(curr.route);
for(Integer idx : list) {
if (visited[idx]==false) {
Node node = new Node(idx, curr.dist+1);
q.add(node);
}
}
}

if (minDist == Integer.MAX_VALUE)
minDist = -1;
return minDist;
}

class Node {
int route;
int dist;

public Node(int route, int dist) {
this.route = route;
this.dist = dist;
}
}
}

Submission Detail

  • 45 / 45 test cases passed.
  • Runtime: 1156 ms, faster than 5.02% of Java online submissions for Bus Routes.
  • Memory Usage: 48.2 MB, less than 100.00% of Java online submissions for Bus Routes.