๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ ํ’€์ด/DFS,BFS

[๋ฐฑ์ค€]4963๋ฒˆ: ์„ฌ์˜ ๊ฐœ์ˆ˜

by syLim___ 2023. 2. 23.
728x90

https://www.acmicpc.net/problem/4963

 

4963๋ฒˆ: ์„ฌ์˜ ๊ฐœ์ˆ˜

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ง€๋„์˜ ๋„ˆ๋น„ w์™€ ๋†’์ด h๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. w์™€ h๋Š” 50๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์–‘์˜ ์ •์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ h๊ฐœ ์ค„์—๋Š” ์ง€๋„

www.acmicpc.net


dfs๋กœ ํ’€์—ˆ๋”๋‹ˆ RecursionError๊ฐ€ ๋‚˜์„œ.. ์ด์œ ๋ฅผ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ

BOJ ์ฑ„์  ์„œ๋น„์Šค์—์„œ๋Š” ํŒŒ์ด์ฌ ์ตœ๋Œ€ ์žฌ๊ท€ ๊นŠ์ด๊ฐ€ 1000์œผ๋กœ ์„ค์ •๋˜์–ด ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค.

๊ทธ๋Ÿฌ๋‹ˆ๊น ํ…Œ์ผ€์ค‘์—์„œ ์žฌ๊ท€๋ฅผ 1000๋ฒˆ ์ด์ƒ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒŒ ์žˆ์—ˆ๋‚˜๋ณด๋‹ค

 

\ํ•ด๊ฒฐ๋ฒ•์€ ์—ฌ๋Ÿฌ ๊ฐ€์ง€๊ฐ€ ์žˆ๋Š”๋ฐ ๊ทธ์ค‘์—์„œ ์ ค ์‰ฌ์šด๊ฑฐ ์„ ํƒํ•จ ^v^

import sys
sys.setrecursionlimit(10**6)

์ตœ๋Œ€์žฌ๊ท€๊นŠ์ด๋ฅผ ์ž„์˜๋กœ ๊ฒ๋‚˜ ํฐ ์ˆ˜๋กœ ์„ค์ •ํ•ด์ฃผ๋ฉด ๋!


import sys
sys.setrecursionlimit(10**6)

#์ƒํ•˜์ขŒ์šฐ๋Œ€๊ฐ์„ 
dx = [-1, -1, -1, 0, 1, 1, 1, 0]
dy = [-1, 0, 1, 1, 1, 0, -1, -1]


def dfs(x, y):
  #๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜์ง€ ์•Š์œผ๋ฉด์„œ ๋ฐฉ๋ฌธํ•œ ์  ์—†์œผ๋ฉด
  if 0 <= x < w and 0 <= y < h and graph[x][y] == 1:
    graph[x][y] = 0  # ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ

    for i in range(8):
      nx = x + dx[i]
      ny = y + dy[i]
      dfs(nx, ny)
    return True #์„ฌ์˜ land์š”์†Œ๋“ค ์ค‘ ์ตœ์ดˆ๋กœ ๋ฐฉ๋ฌธํ•˜๋Š” ์ ๋งŒ True๋ฅผ ๋ฆฌํ„ด
  return False


while True:
  #h,w,๊ทธ๋ž˜ํ”„ ์ •๋ณด ์ž…๋ ฅ๋ฐ›๊ธฐ
  h, w = map(int, input().split())
  if w == 0 and h == 0:
    break

  graph = []
  for i in range(w):
    graph.append(list(map(int, input().split())))

  #์„ฌ์˜ ๊ฐœ์ˆ˜ count
  cnt = 0
  for i in range(w):
    for j in range(h):
      if dfs(i, j) == True: #์ตœ์ดˆ ๋ฐฉ๋ฌธ ์นธ์—์„œ์—๋งŒ cnt๋ฅผ ์ฆ๊ฐ€์‹œ์ผœ์คŒ
        cnt += 1

  print(cnt)

๋ณดํ†ต ํ–‰, ์—ด ์ˆœ์„œ๋กœ ์ž…๋ ฅ๋ฐ›๋Š” ๊ฒŒ ๋งŽ์€๋ฐ ์ด ๋ฌธ์ œ๋Š” ์—ด, ํ–‰ ์ˆœ์œผ๋กœ ์ž…๋ ฅ๋ฐ›๋”๋ž‘


์•ฝ๊ฐ„ ์ฐ์ฐํ•ด์„œ ์žฌ๊ท€๋ฅผ ์•„์˜ˆ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” bfs๋กœ๋„ ํ’€์–ด๋ดค๋‹ค

from collections import deque


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

def bfs(x,y):
  if graph[x][y]==0: #์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ์  ์žˆ์œผ๋ฉด false๋ฆฌํ„ด
    return False
    
  graph[x][y]=0 #๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
  q=deque()
  q.append((x,y))

  while q:
    a,b=q.popleft()
    for i in range(8):
      nx = a + dx[i]
      ny = b + dy[i]
      if 0<=nx<w and 0<=ny<h and graph[nx][ny]==1:
        graph[nx][ny]=0
        q.append((nx,ny))
  return True #์ธ์ ‘ํ•œ ์นธ๋“ค ๋ชจ๋‘ ๋ฐฉ๋ฌธ์ด ๋๋‚˜๋ฉด true๋ฆฌํ„ด



while True:
  h, w = map(int, input().split())
  if w == 0 and h == 0:
    break

  graph = []
  for i in range(w):
    graph.append(list(map(int, input().split())))

  cnt = 0
  for i in range(w):
    for j in range(h):
      if bfs(i, j) == True:
        cnt += 1

  print(cnt)

 

728x90