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

[๋ฐฑ์ค€ 1012] ์œ ๊ธฐ๋† ๋ฐฐ์ถ” (Python)

์€์ง„ 2021. 8. 3. 13:35

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

[๋ฐฑ์ค€ 1012] ์œ ๊ธฐ๋† ๋ฐฐ์ถ” (Python)
๋ฐฑ์ค€


โœ๏ธIdea Sketch

2021-08-02

1. ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ์™€ ๊ฐ™์€ DFS ๋กœ์ง

2. ์˜ค๋žœ๋งŒ์— ํ’€์–ด์„œ ์žŠ์€ ๊ฒƒ

  • main์—์„œ dfs()๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ
  • ์ด์ค‘๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ
  • 2์ฐจ์› ๋ฐฐ์—ด graph ์˜ ๋ชจ๋“  ์›์†Œ๋ฅผ ํ™•์ธํ•œ๋‹ค

3. dx dy ์‚ฌ์šฉ ์‹œ ์†Œ์š”์‹œ๊ฐ„ 4ms ์ฆ๊ฐ€ (96ms)

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def dfs(x, y):
  if (0<=x<n) and (0<=y<m):
    if graph[x][y] == 1:
      graph[x][y] = -1
      for i in range(4):
        dfs(x+dx[i], y+dy[i])
      return True
  return False


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

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

import sys
sys.setrecursionlimit(10**6)

def dfs(x, y):
  if (0<=x<n) and (0<=y<m):
    if graph[x][y] == 1:
      graph[x][y] = -1
      dfs(x-1, y)
      dfs(x+1, y)
      dfs(x, y+1)
      dfs(x, y-1)
      return True
  return False

if __name__ == "__main__":
  t = int(input())
  for _ in range(t):
    n, m, k = map(int, input().split())
    graph = [[0 for _ in range(m)] for _ in range(n)]

    for _ in range(k):
      x, y = map(int, sys.stdin.readline().rstrip().split())
      graph[x][y] = 1

    cnt = 0
    for i in range(n):
      for j in range(m):
        if dfs(i, j) == True:
          cnt += 1

    print(cnt)