Number of Provinces

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
def findCircleNum(self, isConnected):
“””
:type isConnected: List[List[int]]
:rtype: int
“””
“””
DFS the matrix, whenever we run into to a 1, run DFS and clear that island with ans + 1
“””
ans = 0
rowLen = len(isConnected)

visited = [False]*rowLen
def dfs(i):
visited[i] = True
for j in range(rowLen):
if isConnected[i][j] == 1 and not visited[j]:
dfs(j)

for i in range(rowLen):
if not visited[i]:
dfs(i)
ans += 1

return ans

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store