๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“š Algorithm/Baekjoon

[Baekjoon] ๋ฐฑ์ค€ 21736 'ํ—Œ๋‚ด๊ธฐ๋Š” ์นœ๊ตฌ๊ฐ€ ํ•„์š”ํ•ด' ๋ฌธ์ œํ’€์ด Python, ํŒŒ์ด์ฌ, ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ •๋ฆฌ

 
๐Ÿ“ 21736 ๋ฌธ์ œ 

 

์ž…๋ ฅ 

 

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ๋„์—ฐ์ด๊ฐ€ ๋งŒ๋‚  ์ˆ˜ ์žˆ๋Š” ์‚ฌ๋žŒ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ๋‹จ, ์•„๋ฌด๋„ ๋งŒ๋‚˜์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ TT๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

๐Ÿง ํ’€์ด

์œ„์˜ ๋ฌธ์ œ๋Š” ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ์ด๋‹ค.

์บ ํผ์Šค์˜ ํฌ๊ธฐ NxM์„ ์ž…๋ ฅ ๋ฐ›๊ณ , ์บ ํผ์Šค ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ •๋ณด๋ฅผ ์ž…๋ ฅ ๋ฐ›์œผ๋ฉด์„œ ๋„์—ฐ์ด๊ฐ€ ์žˆ๋Š” ๊ณณ์„ ์ฐพ์•„์•ผ ํ•œ๋‹ค. 

'I' ๊ฐ€ ๋‚˜์˜จ ๊ณณ์„ ์ฐพ๊ณ , ๊ทธ ์œ„์น˜๋ฅผ start๋กœ ํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ฒฝ์ด ์•„๋‹ˆ๊ณ , ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์œผ๋ฉฐ 'P'์ธ ๊ฒฝ์šฐ์—๋Š” cnt๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๊ณ , 'X'์ธ ๊ฒฝ์šฐ์—๋Š” ๊ฐ€์ง€ ๋ชปํ•˜๋‹ˆ ๋‹ค์‹œ ํƒ์ƒ‰์„ ํ•ด์•ผํ•œ๋‹ค.  

cnt๊ฐ€ 0์ด ์•„๋‹ˆ๋ผ๋ฉด 'TT'๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. 

 

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
N, M = map(int, input().split())
campus = []


#์ž…๋ ฅ ๋ฐ›์œผ๋ฉด์„œ ๋„์—ฐ์ด๊ฐ€ ์žˆ๋Š” ๊ณณ์„ ์ฐพ๊ธฐ 
for i in range(N) :
    r = list(input().rstrip())
    for j in range(M) :
        if r[j] == 'I' :
            start = [i, j]
    campus.append(r)
    
    
#์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰ํ•˜๊ธฐ ์œ„ํ•จ            
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
visited = [[False] * M for _ in range(N)]
cnt = 0


def dfs(x, y) :
    global cnt 
    
    if 0<=x<N and 0<=y<M and not visited[x][y]:
        visited[x][y] = True
        if campus[x][y] == 'P' :	#์‚ฌ๋žŒ์ด ์žˆ๋Š” ๊ณณ์ด๋ผ๋ฉด	
            cnt += 1	#cnt ์ฆ๊ฐ€
        for i in range(4) :
            nx = x + dx[i]
            ny = y + dy[i]  
            if 0<=nx<N and 0<=ny<M :
                if campus[nx][ny] != 'X' and not visited[nx][ny] :
                    dfs(nx, ny)
dfs(start[0], start[1])
            
      

if cnt > 0 : 
    print(cnt)
else :
    print('TT')

 

 

 

728x90