7576 : 토마토

서희찬·2021년 10월 14일
0

백준

목록 보기
64/105

문제

코드

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**)

dx = [1,-1,0,0,1,1,-1,-1]
dy = [0,0,-1,1,1,-1,1,-1] #대각선 벡터도 추가 

def dfs(x,y):
  graph[x][y]=0 #방문 ! 
  for i in range(8):
      cx = x+dx[i]
      cy = y+dy[i]
      if 0<=cx<n  and 0<=cy<m and graph[cx][cy]==1:
        dfs(cx,cy)

while True :
    cnt=0
    m,n = map(int,input().split())
    if(m==n==0):
        break
    graph=[]

    for i in range(n):
        graph.append(list(map(int, input().rstrip().split()))) #입력받기 

    for j in range(n):
        for k in range(m):
            if (graph[j][k]==1):
                dfs(j,k)
                cnt+=1
    print(cnt)    

해설

이전문제들과 비슷하지만 섬의 갯수를 셀때 편의성을 위해 BFS가 아닌 DFS로 구현했으며
가로 방향의 벡터들까지 만들어주기 위해서 dx,dy에 방향벡터를 추가해주어 가로까지 탐색할 수 있게 만들었다.
그러고 1을 0으로 바꿔 섬을 전부 없애주는 방식으로 탐색을진행했다.

profile
부족한 실력을 엉덩이 힘으로 채워나가는 개발자 서희찬입니다 :)

0개의 댓글