Description
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.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
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.
Return the total number of provinces.
Example 1:
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Example 2:
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
My solution
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
# 특정 원소가 속한 집합을 찾기
def find_parent(parent, x):
# 루트 노드를 찾을 때 까지 재귀 호출
if parent[x] != x :
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
v = len(isConnected)
parent = [0] * v
for i in range(v):
parent[i] = i
for i, con in enumerate(isConnected):
for j, k in enumerate(con):
if (k == 1) and (i != j):
union_parent(parent, i, j)
print(parent)
s = set()
for i in parent:
s.add(find_parent(parent, i))
return len(s)
Other Solution
class DSU:
def __init__(self, N):
self.par = list(range(N))
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
self.par[self.find(x)] = self.find(y)
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
N = len(isConnected)
dsu = DSU(N)
for i in range(1, N):
for j in range(i):
if isConnected[i][j] == 1:
dsu.union(i, j)
s = set()
for p in dsu.par:
s.add(dsu.find(p))
return len(s)
기존에 짰던 코드가 오류가 계속 나타나 사람들이 풀이한 방법을 이용하였다. 기존 방법의 문제는 par리스트 자체를 return을 해 문제가 발생하였음을 확인할 수 있었고, 각 par리스트 안의 원소들의 parent를 찾아주면 정확한 결과를 낼 수 있다.
문제 출처 : https://leetcode.com/problems/number-of-provinces/
'Algorithm > Daily Coding Tests Challenge' 카테고리의 다른 글
[Leetcode] Medium : Corporate Flight Bookings (0) | 2021.11.15 |
---|---|
[Leetcode] Medium : Sum of Square Numbers (0) | 2021.11.15 |
[Leetcode] Medium : Network Delay time (0) | 2021.10.13 |
[Leetcode] Easy: Pascal's Triangle 2 (0) | 2021.10.10 |
[Leetcode] Easy : Pascal's Triangle (0) | 2021.10.10 |