Algorithem/백준 PS with code

백준 #21610 - [G5] 마법사 상어와 비바라기 : 구현

jamong5 2023. 6. 1. 12:01

(python3)

 

21610번: 마법사 상어와 비바라기

마법사 상어는 파이어볼, 토네이도, 파이어스톰, 물복사버그 마법을 할 수 있다. 오늘 새로 배운 마법은 비바라기이다. 비바라기를 시전하면 하늘에 비구름을 만들 수 있다. 오늘은 비바라기

www.acmicpc.net

 

 

단계 분리해서 작성하기

단순 시뮬레이션 구현이라 특별한 접근법이 있지는 않습니다. 복잡한 단계들을 쪼개서 구현하면 접근하기가 쉽습니다. 문제에서 주어진 단계별로 함수를 분리해서 구현했습니다.

 

코드

def solution(input) : 
    N,M = list(map(int,input().split()))
    wmap = []
    for _ in range(N) :
        wmap.append(list(map(int,input().split())))
    GO = []
    for _ in range(M) :
        GO.append(tuple(map(int,input().split())))
    D = [(),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1)] # 1~8 까지 D

    cloud = [(N-1,0),(N-1,1),(N-2,0),(N-2,1)]

    def round1(cloud, d, s) :
        dr, dc = D[d][0] * s, D[d][1] * s
        move_cloud = []
        for cr,cc in cloud :
            cr = (cr+dr+N)%N
            cc = (cc+dc+N)%N
            move_cloud.append((cr,cc))
        return move_cloud
    
    def round2(cloud) :
        for cr, cc in cloud :
            wmap[cr][cc] += 1
    
    def round4(b_cloud) :
        for cr,cc in b_cloud :
            cnt = 0
            for dr,dc in [D[2],D[4],D[6],D[8]] :
                nr = cr+dr
                nc = cc+dc
                if nr >= 0  and nr < N and nc >=0 and nc < N :
                    if wmap[nr][nc] >= 1 :
                        cnt += 1
            wmap[cr][cc] += cnt

    def round5(b_cloud) :
        cloud = []
        for r in range(N) :
            for c in range(N) :
                if (r,c) in b_cloud :
                    continue
                if wmap[r][c] >= 2 :
                    cloud.append((r,c))
                    wmap[r][c] -= 2
        return cloud

    def cnt_w() :
        cnt = 0
        for r in range(N) :
            for c in range(N) :
                cnt+=wmap[r][c]
        return cnt
        
    for go in GO :
        cloud = round1(cloud,*go)
        round2(cloud)
        b_cloud = cloud
        round4(b_cloud)
        cloud = round5(b_cloud)

    print(cnt_w())

solution(input)

 

my solved.ac :

 

solved.ac

알고리즘 문제해결 학습의 이정표 🚩 Baekjoon Online Judge 문제들의 난이도 및 티어 정보를 제공하는 사이트입니다.

solved.ac