Problem
Solution
DFS problem
Each row = One city
Don't need to look at one more than once -- keep track of them in 'seen' dictionary.
Time Complexity
O(n) (n = num of cities)
Space Complexity
O(N)
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
if not isConnected:
return 0
rows = len(isConnected)
seen = set()
count = 0
def dfs(r):
for index, val in enumerate(isConnected[r]):
if val == 1 and index not in seen:
seen.add(index)
dfs(index)
for r in range(rows):
if r not in seen:
dfs(r)
count +=1
return count
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[Coderust] Find Smallest Common Element in All Rows (0) | 2022.02.22 |
---|---|
[Coderust] Search in Rotated Sorted Array (0) | 2022.02.14 |
[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal (0) | 2021.10.29 |
[LeetCode] Clone Graph (0) | 2021.10.27 |
[LeetCode] Lowest Common Ancestor of a Binary Search Tree (0) | 2021.10.24 |