ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[๋ฐฑ์ค€ 7576] ํ† ๋งˆํ†  (Python)

์€์ง„ 2021. 8. 4. 01:05

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[๋ฐฑ์ค€ 7576] ํ† ๋งˆํ†  (Python)
๋ฐฑ์ค€


โœ๏ธIdea Sketch

2021-08-02

1. ์˜ˆ์ƒ ์ถœ๋ ฅ๊ฐ’

1) ์ฒ˜์Œ๋ถ€ํ„ฐ ๋ชจ๋‘ ์ต์€ ๊ฒฝ์šฐ, ์ฆ‰ ์ž…๋ ฅ๊ฐ’์— 0์ด ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” 0์„ ์ถœ๋ ฅํ•œ๋‹ค.
2) 0์ด ๋ชจ๋‘ 1์ด ๋˜๊ธฐ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” ์ตœ์†Œ ๋‚ ์งœ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
3) ๋ชจ๋‘ ์ต์ง€๋Š” ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ, ์ฆ‰ ๋ชจ๋“  ์—ฐ์‚ฐ์ด ๋๋‚œ ํ›„์—๋„ 0์ด ๋‚จ์•„์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” -1์„ ์ถœ๋ ฅํ•œ๋‹ค.

2. main ๋กœ์ง

  • ์ž…๋ ฅ๊ฐ’์„ ๋ฐ›์•„ graph ์— ์ •๋ฆฌํ•œ๋‹ค.
  • ์ต์€ ํ† ๋งˆํ† ์˜ x, y ์ธ๋ฑ์Šค๋ฅผ queue์— ์ €์žฅํ•œ๋‹ค.
  • queue์˜ ์ฒซ๋ฒˆ์งธ ์š”์†Œ x, y๋ฅผ popํ•œ๋‹ค.
  • dfs ์—ฐ์‚ฐ์„ ํ•˜๊ธฐ ์œ„ํ•ด ๋ฐฉ๋ฌธ์—ฌ๋ถ€๋ฅผ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค. (visited[y][x] = 0)
  • dfs(x, y) ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

3. DFS ๋กœ์ง

  • ๊ฒฝ๊ณ„๊ฐ’์„ ๋ถ„์„ํ•œ๋‹ค.
  • ์ฒ˜์Œ ๋ฐฉ๋ฌธํ•˜๋ฉด์„œ
    1) ์ต์€ ํ† ๋งˆํ† ์ผ ๊ฒฝ์šฐ, ์ƒํ•˜์ขŒ์šฐ ์ธ์ ‘ํ•œ ๊ณณ์— ์žˆ๋Š” ํ† ๋งˆํ† ์—๊ฒŒ ์˜ํ–ฅ์„ ๋ผ์นœ๋‹ค.
    2) ์ต์ง€ ์•Š๋Š” ํ† ๋งˆํ† ์ผ ๊ฒฝ์šฐ ์ต์œผ๋ฉฐ, ์ด ํ† ๋งˆํ† ์˜ x, y ์ธ๋ฑ์Šค๋ฅผ queue์— ์ถ”๊ฐ€ํ•œ๋‹ค.


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-08-02 3528ms ํ†ต๊ณผ

  • ๋” ํšจ์œจ์ ์ธ ๋กœ์ง ์กด์žฌ
from collections import deque
import sys
sys.setrecursionlimit(10**6)

def dfs(x, y):
  if (0<=x<m) and (0<=y<n) and visited[y][x] == 0:
    visited[y][x] = 1
    if graph[y][x] == 1:
      dfs(x, y-1)
      dfs(x, y+1)
      dfs(x-1, y)
      dfs(x+1, y)
    if graph[y][x] == 0:
      graph[y][x] = 1
      queue_x.append(x)
      queue_y.append(y)
    return True

if __name__ == "__main__":
  m, n = map(int, input().split())
  graph = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(n)]
  visited = [[0 for _ in range(m)] for _ in range(n)]

  queue_x = deque([])
  queue_y = deque([])
  flag_0 = False 

  for i in range(n):
    if 1 in graph[i]:  
      for j in range(m):
        if graph[i][j] == 1:
          queue_x.append(j)
          queue_y.append(i)
    if 0 in graph[i]:
      flag_0 = True

  if flag_0 == False:  #1 : ์ฒ˜์Œ๋ถ€ํ„ฐ 0์ด ํ•˜๋‚˜๋„ ์—†๋Š” ๊ฒฝ์šฐ
    print(0)
    sys.exit(0)

  result = 0  #2 : 0์ด ๋ชจ๋‘ 1์ด ๋˜๊ธฐ๊นŒ์ง€ ์ตœ์†Œ ์†Œ์š” ๋‚ ์งœ
  while len(queue_x) != 0:
    l = len(queue_x)
    for _ in range(l):
      x = queue_x.popleft()
      y = queue_y.popleft()
      visited[y][x] = 0
      dfs(x, y)
    result += 1

  for i in graph:  #3 : ์—ฐ์‚ฐ ํ›„์—๋„ 0์ด ๋‚จ์•„์žˆ๋Š” ๊ฒฝ์šฐ
    if 0 in i:
      print(-1)
      sys.exit(0)

  print(result-1)