Skip to content

Commit 9bb99f5

Browse files
committed
Added medium problem.
1 parent f07edf2 commit 9bb99f5

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
# NUMBER OF PROVINCES
3+
4+
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
5+
6+
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
7+
8+
You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
9+
10+
Return the total number of provinces.
11+
12+
Example 1:
13+
14+
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
15+
Output: 2
16+
Example 2:
17+
18+
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
19+
Output: 3
20+
21+
Constraints:
22+
23+
1 <= n <= 200
24+
n == isConnected.length
25+
n == isConnected[i].length
26+
isConnected[i][j] is 1 or 0.
27+
isConnected[i][i] == 1
28+
isConnected[i][j] == isConnected[j][i]
29+
"""
30+
31+
class Solution:
32+
def findCircleNum(self, isConnected):
33+
graph = {}
34+
n = len(isConnected)
35+
for i in range(n):
36+
graph[i] = []
37+
for j in range(n):
38+
if isConnected[i][j] == 1:
39+
graph[i].append(j)
40+
print(graph)
41+
provinces = 0
42+
visited = set()
43+
for i in range(n):
44+
if i not in visited:
45+
provinces += 1
46+
self.runDfs(i, graph, visited)
47+
48+
return provinces
49+
50+
def runDfs(self, current, graph, visited):
51+
if current in visited:
52+
return
53+
54+
visited.add(current)
55+
for neighbor in graph[current]:
56+
self.runDfs(neighbor, graph, visited)
57+
return

0 commit comments

Comments
 (0)