programmers 행렬과 연산 python
2022년 12월 07일
#algorithm#python#programmers#queue

문제

행렬과 연산

풀이

표를 적당히 쪼개서 deque로 풀면 된다. 맨 왼쪽 열과 맨 오른쪽 열을 따로 저장해서 deque 2개를 만들고, 각 행의 인덱스를 저장한 deque를 만든다. ShiftRow 연산 시, q, leftq, rightq에 저장된 마지막 인덱스를 맨 앞으로 옮겨준다. Rotate 연산 시, leftq, rightq에서 값을 적절히 옮겨준다. 행의 길이가 2일 때는 rcq가 비어있기 때문에, 다르게 처리해야한다.

굳이 인덱스를 q에 저장해서 마지막에 옮길 필요는 없을 것 같다.

Desktop View

풀이 코드

from collections import deque
def solution(rc, operations):
    
    answer = []
 
    h = len(rc)
    q = deque(i for i in range(h))
    rcq = list(map(deque, rc))
    qleft, qright = deque(), deque()
    for i in range(h):
        qleft.append(rcq[i].popleft())
        qright.append(rcq[i].pop())
        
    # query 연산
    for oper in operations:
        if oper[0] == "R": #Rotate
            topIdx = q.popleft()
            q.appendleft(topIdx)
            bottomIdx = q.pop()
            q.append(bottomIdx)
            if len(rcq[0])==0: # 행의 길이가 2인 경우
                qright.appendleft(qleft.popleft())
                qleft.append(qright.pop())
                
            else: # 행의 길이가 2가 아닌 경우
                qright.appendleft(rcq[topIdx].pop())
                qleft.append(rcq[bottomIdx].popleft())
                rcq[bottomIdx].append(qright.pop())
                rcq[topIdx].appendleft(qleft.popleft())
            
        else: #ShiftRow
            q.appendleft(q.pop())
            qleft.appendleft(qleft.pop())
            qright.appendleft(qright.pop())
	
	# q에 저장된 index에 맞게 행 옮기기 
    topIdx = q.popleft()
    temprcq = deque()
    for i in range((h-topIdx)%h):
        temprcq.appendleft(rcq.pop())
    answer = list(temprcq)+list(rcq)
    
    # qrc, qleft, qright 합치기
    for i in range(h):
        answer[i].appendleft(qleft.popleft())
        answer[i].append(qright.popleft())
    answer = list(map(list, answer))
 
    return answer