백준 구현 대비 낚시왕

yjkim·2023년 7월 12일
0

알고리즘

목록 보기
29/59

문제:https://www.acmicpc.net/problem/17143

접근

위 문제를 도식화하면 다음과 같다
낚시꾼이 상어를 잡음->상어가 움직임
두 행위를 함수로 각각 정의해주면 됨.

위 문제를 풀면서 moveshark함수에서 자꾸 graph가 정의되어 있지 않다고 오류가 떳음. 문제는 다음 코드에 있었다.

  graph=[item[:] for item in tempgraph] # 이것 떄문 이었다. # 할당 연산이 발생하는 순간 지역변수라고 생각하게 된다.

함수 내애서 그래프가 할당되는 순간 그 그래프는 global 처리가 되어 있지 않는 이상 지역변수라고 취급을 받게된다. 즉 global 이 선언되지 않았으면 graph는 지역변수 취급을 받게되고 moveshark내에서 graph가 정의된 부분을 찾는것이다. 그러나 graph는 함수 밖에서 정의된 전역변수기 때문에 에러가 났던것. 전역으로 선언된 그래프를 갱신할때는 global처리를 꼭 해주도록 하자

from collections import deque
def catchshark(fisherman):
  global total
  for i in range(R):
    if graph[i][fisherman]!=0:
      total+=graph[i][fisherman][2]
      graph[i][fisherman]=0
      return 


def moveshark():
  global graph
  tempgraph=[[0 for i in range(C)] for j in range(R)]
  for i in range(R):
    for j in range(C):
      if graph[i][j]!=0:
        s,d,z=graph[i][j][0],graph[i][j][1],graph[i][j][2]
        count=0
        ni,nj=i,j
        if d==0 or d==1:
            if R>2:
              s=s%(2*R-2)
        else:
            if C>2:
              s=s%(2*C-2)
        while count<s:
          if 0<=ni+directions[d][0]<R and 0<=nj+directions[d][1]<C:
            ni,nj=ni+directions[d][0],nj+directions[d][1]
          else:
            if d==0 or d==2:
              d+=1
            else:
              d-=1
            ni,nj=ni+directions[d][0], nj+directions[d][1]
          count+=1
        graph[i][j][1]=d
        if tempgraph[ni][nj]==0:
          tempgraph[ni][nj]=graph[i][j]
        else:
          if z>tempgraph[ni][nj][2]:
            tempgraph[ni][nj]=graph[i][j]

  graph=[item[:] for item in tempgraph] # 이것 떄문 이었다. # 할당 연산이 발생하는 순간 지역변수라고 생각하게 된다.



R,C,M=map(int, input().split())
total=0
graph=[[0 for i in range(C)]for j in range(R)]
queue=deque()

directions=[[-1,0],[1,0],[0,1],[0,-1]]
for i in range(M):
  r,c,s,d,z=map(int, input().split())
  graph[r-1][c-1]=[s,d-1,z]



for i in range(C):
  catchshark(i)
  moveshark()

print(total)
profile
컴퓨터 공부 / 백엔드 개발

0개의 댓글