์ƒˆ์†Œ์‹

๐Ÿงฎ PS

๋ฐฑ์ค€ (boj) ํŒŒ์ด์ฌ - 10026 : ์ ๋ก์ƒ‰์•ฝ

  • -

#๋ฌธ์ œ๋งํฌ : https://www.acmicpc.net/problem/10026

 

10026๋ฒˆ: ์ ๋ก์ƒ‰์•ฝ

์ ๋ก์ƒ‰์•ฝ์€ ๋นจ๊ฐ„์ƒ‰๊ณผ ์ดˆ๋ก์ƒ‰์˜ ์ฐจ์ด๋ฅผ ๊ฑฐ์˜ ๋Š๋ผ์ง€ ๋ชปํ•œ๋‹ค. ๋”ฐ๋ผ์„œ, ์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ์€ ์•„๋‹Œ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ๊ณผ๋Š” ์ข€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ๋‹ค. ํฌ๊ธฐ๊ฐ€ N×N์ธ ๊ทธ๋ฆฌ๋“œ์˜ ๊ฐ ์นธ์— R(๋นจ๊ฐ•), G(์ดˆ๋ก)

www.acmicpc.net

 

# ๋ถ„๋ฅ˜ : dfs

 

# ๋‚œ์ด๋„ : Gold 5

 

 

์ ๋ก์ƒ‰์•ฝ์ธ ๊ฒฝ์šฐ, ์ ๋ก์ƒ‰์•ฝ์ด ์•„๋‹Œ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ„์–ด ์ด 2๋ฒˆ dfs๋ฅผ ๋Œ๋ ธ๋‹ค. ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ์šฐ๋ ค๋˜์—ˆ์œผ๋‚˜ ์ž…๋ ฅ์ด 100์ค„ ์ดํ•˜๋ผ์„œ ๋ฌธ์ œ์—†์ด ํ†ต๊ณผ ๋˜์—ˆ๋‹ค. 

 

#์ฝ”๋“œ(Python)

from sys import setrecursionlimit

setrecursionlimit(10000)
n = int(input())
grid = []
visited = [[False for i in range(n)] for i in range(n)]

cnt = 0
for _ in range(n):
    grid.append(list(input()))

color = ""
colors = []
colors2 = []


def is_valid(x,y):
    if x >= 0 and x < n and y >= 0 and y < n:
        return True
    return False

def dfs(g,x,y):
    global color 
    if not is_valid(x,y):
        return False
    if visited[x][y] == False and g[x][y] == color:
        visited[x][y] = True
        global cnt
        cnt += 1
        dfs(g,x-1,y)
        dfs(g,x+1,y)
        dfs(g,x,y+1)
        dfs(g,x,y-1)
        return True
    return False

for x in range(n):
    for y in range(n):
        if grid[x][y] != 0:
            color = grid[x][y]
            if dfs(grid,x,y):
                colors.append(color)

visited = [[False for i in range(n)] for i in range(n)]

for x in range(n):
    for y in range(n):
        if grid[x][y] == "R":
            grid[x][y] = "G"

for x in range(n):
    for y in range(n):
        if grid[x][y] != 0:
            color = grid[x][y]
            if dfs(grid,x,y):
                colors2.append(color)

print(len(colors) , len(colors2))
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.