๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 6186 - Best Grass

by HandHand 2021. 3. 8.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 6186๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ธ์ ‘ํ•œ ์ž”๋”” ๋ญ‰์น˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ž”๋”” ๋ญ‰์น˜๋Š” ์„œ๋กœ ์ธ์ ‘ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ ์ขŒํ‘œ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ์ž”๋””๊ฐ€ ๋ฐœ๊ฒฌ๋˜๋ฉด ์ธ์ ‘ํ•œ ๋„ค ๋ฐฉํ–ฅ์„ ๋ชจ๋‘

๋ฐฉ๋ฌธํ•ด๋ณด๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๋ชจ๋“  ์ž”๋”” ๋ญ‰์น˜๋ฅผ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys

R, C = list(map(int, sys.stdin.readline().split()))
grass = [list(sys.stdin.readline().strip()) for _ in range(R)]

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


def solution():
    clump = 0
    visit = [[0] * C for _ in range(R)]

    for r in range(R):
        for c in range(C):
            if not visit[r][c] and grass[r][c] == '#':
                visit[r][c] = 1
                clump += 1

                for i in range(4):
                    nr, nc = r + dx[i], c + dy[i]
                    if 0 <= nr < R and 0 <= nc < C:
                        if not visit[nr][nc]:
                            visit[nr][nc] = 1

    return clump


print(solution())
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€