하루일문
[백준] 14716 현수막 (파이썬) 본문
문제
14716번: 현수막
혁진이의 생각대로 프로그램을 구현했을 때, 현수막에서 글자의 개수가 몇 개인지 출력하여라.
www.acmicpc.net
코드
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
dx = [1, 1, 1, 0, 0, -1, -1, -1]
dy = [-1, 0, 1, -1, 1, 1, 0, -1]
def DFS(graph, visited, i, j):
visited[i][j] = True
for _ in range(8):
X = i + dx[_]
Y = j + dy[_]
if 0 <= X < M and 0 <= Y < N and visited[X][Y] == False and graph[X][Y] == "1":
visited[X][Y] = True
DFS(graph, visited, X, Y)
M, N = map(int, input().split())
graph = []
visited = [[False] * N for _ in range(M)]
for _ in range(M):
graph.append(list(input().strip().split()))
cnt = 0
for i in range(M):
for j in range(N):
if graph[i][j] == "1" and visited[i][j] == False:
DFS(graph, visited, i, j)
cnt += 1
print(cnt)
해설
DFS방식으로 1이면서 방문하지 않는곳에 들어가 8방향으로 움직이면서 연결된 부분의 합을 구해서 풀었다.
'algorithm > baekjoon' 카테고리의 다른 글
[백준] 11060번 점프점프(파이썬) (0) | 2023.03.12 |
---|---|
[백준] 17298 오큰수 (파이썬) (0) | 2023.03.11 |
[백준] 11478번 서로다른 문자열 개수(파이썬) (0) | 2023.03.09 |
[백준] 10815 숫자카드(파이썬) (0) | 2023.03.08 |
[백준] 10799 쇠막대기(파이썬) (0) | 2023.03.07 |