Skip to content

Commit 0b45cc6

Browse files
committed
547. Number of Provinces
1 parent 2045bb5 commit 0b45cc6

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
object Solution {
2+
3+
def dfs(graph: Map[Int, Set[Int]], start: Int, visited: Set[Int] = Set.empty): Set[Int] = {
4+
if (visited.contains(start)) visited
5+
else graph.getOrElse(start, Nil).foldLeft(visited + start)(
6+
(acc, neighbor) => dfs(graph, neighbor, acc)
7+
)
8+
}
9+
10+
// stupid solution
11+
def findCircleNum(isConnected: Array[Array[Int]]): Int = {
12+
val graph = scala.collection.mutable.Map.empty[Int, Set[Int]]
13+
val n = isConnected.length
14+
var i = 0
15+
while (i < n) {
16+
var j = 0
17+
while (j < n) {
18+
if (isConnected(i)(j) == 1) {
19+
graph.addOne(i, graph.get(i).toSet.flatten + j)
20+
}
21+
j += 1
22+
}
23+
i += 1
24+
}
25+
26+
val circles = scala.collection.mutable.ArrayBuffer.empty[Set[Int]]
27+
isConnected.indices.foreach(
28+
i => if (!circles.exists(_.exists(_ == i))) circles.addOne(dfs(graph.toMap, i))
29+
)
30+
31+
circles.size
32+
}
33+
}
34+
35+
object Solution2 {
36+
def findCircleNum(isConnected: Array[Array[Int]]): Int = {
37+
val n = isConnected.length
38+
val visited = Array.fill(n)(false)
39+
40+
def dfs(city: Int): Unit = {
41+
for (neighbor <- 0 until n) {
42+
if (isConnected(city)(neighbor) == 1 && !visited(neighbor)) {
43+
visited(neighbor) = true
44+
dfs(neighbor)
45+
}
46+
}
47+
}
48+
49+
var provinces = 0
50+
51+
for (i <- 0 until n) {
52+
if (!visited(i)) {
53+
provinces += 1
54+
visited(i) = true
55+
dfs(i)
56+
}
57+
}
58+
provinces
59+
}
60+
}
61+
62+
Solution2.findCircleNum(Array(Array(1, 1, 0), Array(1, 1, 0), Array(0, 0, 1)))
63+
Solution2.findCircleNum(Array(Array(1, 0, 0), Array(0, 1, 0), Array(0, 0, 1)))

0 commit comments

Comments
 (0)