배울점: 코드가 길어질수록 컨트롤하기가 어려워진다. 특히 함수 내에서 매개변수를 쓰지 않고 글로벌 변수로 다루게 되면 이게 상당히 복잡해진다. 따라서 매개변수로 컨트롤하는게 그나마 디버깅할 때 덜 힘들 방법이라고 생각한다.
import sys
import copy
def debug(graph):
print()
for x in range(1,1+r):
for y in range(1,1+c):
if graph[x][y]:
print(graph[x][y], end=' ')
else:
print("NONE", end=' ')
print()
print()
input=sys.stdin.readline
r, c, m = map(int,input().split())
graph=[[[] for i in range(1+c)] for _ in range(1+r)]
#잡은 사이즈 총합
totsize=0
#shark의 위치 정보
sharks=[]
#fisher의 처음 위치
fisher=(1,0)
#1부터 4까지 위, 아래, 오른쪽, 왼쪽
dx=[0,-1,1,0,0]
dy=[0,0,0,1,-1]
for x in range(m):
sr, sc, s, d, z = map(int,input().split())
graph[sr][sc].append((z, s, d))
sharks.append((sr,sc))
def fisher_move_and_fish(start):
#move
x, y = start
nx = x
ny = y + 1
#x는 고정된 위치이므로
if (1<=ny<=c):
for i in range(1, r+1):
if graph[i][ny]:
global totsize
#상어는 한칸에 한마리밖에 없으므로 sort 필요 없음
totsize += graph[i][ny][0][0]
#상어가 사라짐
del graph[i][ny][0]
#sharks의 위치 정보도 없어짐
sharks.remove((i,ny))
#fisher의 위치 리턴
return(nx,ny)
return (nx,ny)
def shark_move(shark):
#shark 한마리가 움직임 shark는 위치 정보
x, y = shark
#안움직였을때를 위해
nx=x
ny=y
#graph는 원본
z, s, d= graph[x][y][0]
#s는 움직이는 횟수, d는 방향
for i in range(s):
nx = x+dx[d]
ny = y+dy[d]
if not (1<=nx<=r and 1<=ny<=c):
# d가 위,아래이면
if d // 3 == 0:
if d==1:
d=2
else:
d=1
else:
if d==3:
d=4
else:
d=3
nx = x+dx[d]
ny = y+dy[d]
x,y= nx,ny
# 다 움직이고 난 후 새로운 그래프에 저장
copygraph[nx][ny].append((z, s, d))
newsharks.append((nx,ny))
#sharks는 그 위치에 있는 상어들의 나열
def shark_eat(sharks):
sharks.sort(reverse=True)
return sharks[0]
x, y = fisher
while y < c:
x, y =fisher_move_and_fish((x,y))
copygraph=[[[] for i in range(1+c)] for _ in range(1+r)]
#sharks의 바뀐 위치를 저장
newsharks=[]
#print(sharks)
for shark in sharks:
shark_move(shark)
sharks=newsharks
sharks=list(set(sharks))
#print(sharks)
#debug(graph)
graph=[[[] for i in range(1+c)] for _ in range(1+r)]
for i in range(1,r+1):
for j in range(1,c+1):
if copygraph[i][j]:
live_shark=shark_eat(copygraph[i][j])
graph[i][j].append(live_shark)
#debug(graph)
print(totsize)