python - leetcode - 547 - ๋ชจ๋ฉ˜ํŠธ

* * * ๋ฌธ์ œ ๋ฒˆํ˜ธ: * 547 * * * ๋ฌธ์ œ: * * ์นœ๊ตฌ ๊ถŒ * * ๋‚œ์ด๋„: * * ์ค‘๊ฐ„ * ๋‚ด์šฉ: * * ๋ฐ˜ ์— N ๋ช…์˜ ํ•™์ƒ ์ด ์žˆ ์Šต ๋‹ˆ ๋‹ค.๊ทธ ์ค‘ ์–ด๋–ค ์‚ฌ๋žŒ ์€ ์นœ๊ตฌ ์ด ๊ณ , ์–ด๋–ค ์‚ฌ๋žŒ ์€ ๊ทธ๋ ‡์ง€ ์•Š๋‹ค.๊ทธ๋“ค์˜ ์šฐ์ • ์€ ์ „๋‹ฌ ์„ฑ ์„ ๊ฐ€์ง€ ๊ณ  ์žˆ๋‹ค.A ๋Š” B ์˜ ์นœ๊ตฌ ์ด ๊ณ  B ๋Š” C ์˜ ์นœ๊ตฌ ๋ผ ๋Š” ๊ฒƒ ์„ ์•Œ ๊ณ  ์žˆ๋‹ค ๋ฉด ์šฐ ๋ฆฌ ๋Š” A ๋„ C ์˜ ์นœ๊ตฌ ๋ผ ๊ณ  ์ƒ๊ฐ ํ•  ์ˆ˜ ์žˆ๋‹ค.์ด๋ฅธ๋ฐ” ์นœ๊ตฌ ๊ถŒ ์ด๋ž€ ๋ชจ๋“  ์นœ๊ตฌ ์˜ ์ง‘ํ•ฉ ์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค.
N N ์˜ ํ–‰๋ ฌ M ์„ ์ง€์ • ํ•˜์—ฌ ํ•™๊ธ‰ ์ค‘ ํ•™์ƒ ๊ฐ„ ์˜ ์นœ๊ตฌ ๊ด€ ๊ณ„ ๋ฅผ ๋‚˜ํƒ€ ๋‚ธ๋‹ค.๋งŒ์•ฝ ์— M [i] [j] = 1 ์€ i ๋ฒˆ ์งธ ์™€ j ๋ฒˆ ์งธ ํ•™์ƒ ์ด ์„œ๋กœ ์นœ๊ตฌ ๊ฐ€ ๋˜ ๋Š” ๊ฒƒ ์„ ์•Œ ๊ณ  ์žˆ ์Œ ์„ ๋‚˜ํƒ€ ๋‚ธ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š ์œผ ๋ฉด ๋ชจ๋ฅธ๋‹ค.๋„ˆ ๋Š” ๋ชจ๋“  ํ•™์ƒ ๋“ค ์ด ์ด๋ฏธ ์•Œ ๊ณ  ์žˆ ๋Š” ์นœ๊ตฌ ๊ถŒ ์˜ ์ด ์ˆ˜ ๋ฅผ ์ถœ๋ ฅ ํ•ด ์•ผ ํ•œ๋‹ค.
์˜ˆ์‹œ 1:
  : 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
  : 2 
  ๏ผš     0   1    ๏ผŒ        ใ€‚
 2           ใ€‚    2ใ€‚

์˜ˆ์‹œ 2:
  : 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
  : 1
  ๏ผš     0   1    ๏ผŒ  1   2    ๏ผŒ    0   2    ๏ผŒ            ๏ผŒ  1ใ€‚

์ฃผ์˜:
N ์€ [1, 200] ์˜ ๋ฒ”์œ„ ๋‚ด ์— ์žˆ๋‹ค
4. 567917. ๋ชจ๋“  ํ•™์ƒ ์— ๊ฒŒ M [i] [i] = 1 ์ด ์žˆ ์Šต ๋‹ˆ ๋‹ค
4. 567917. M [i] [j] = 1 ์ด ์žˆ ์œผ ๋ฉด M [j] [i] = 1 ์ด ์žˆ๋‹ค
์ฝ”๋“œ ๋Š” ๋‹ค์Œ ๊ณผ ๊ฐ™ ์Šต ๋‹ˆ ๋‹ค:
class Solution:
    def findCircleNum(self, M: 'List[List[int]]') -> 'int':
        visited = [0 for _ in range(len(M))]
        n = len(M)
        res = 0
        for i in range(n):
            if visited[i] == 0:
                res += 1
                self.dfs(M, i, visited)
        return res
    
    def dfs(self, M, i, visited):
        visited[i] = 1
        for j in range(len(M)):
            if M[i][j] != 0 and visited[j] == 0:
                self.dfs(M, j, visited)

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ