[백준] 16927번: 배열 돌리기2

Chaejung·2023년 6월 11일
0

알고리즘_Python

목록 보기
22/22
post-thumbnail

문제

배열 돌리기1과 동일한 문제지만은, 제한 조건이 다르다. 1은 회전 수가 10^3까지지만, 2는 회전 수가 10^9까지이다. 따라서 아마 1과 동일한 코드지만 제출 시 시간초과가 나는 경우가 발생할 것이다.

풀이 전 생각했던 방향

나는 구현문제에서 주로 단계 별로 함수를 만든다.
갯수 세기, 전체 정보 변경이 아니라면 전역으로 관리하는 변수가 아니라 오로지 함수 출력으로 결과를 내놓도록, 되도록 순수함수로 만들려고 한다.

그래서 이 문제에서는 다음과 같은 단계로 함수가 만들어진다.

풀이

# https://www.acmicpc.net/problem/16927
N, M, R = map(int, input().split())

originArray = []
for _ in range(N):
    eachRow = list(map(int, input().split()))
    originArray.append(eachRow)


def makeCircuitSet(n, m):
    spList = [(0, 0)]
    startPoint = (0, 0)
    while (startPoint[0] < n//2-1 and startPoint[1] < m//2-1):
        startPoint = (startPoint[0]+1, startPoint[1]+1)
        spList.append(startPoint)

    circuitList = []
    limitR, limitC = (n, m)
    for point in spList:
        pointList = []
        for down in range(point[0], limitR-1):
            pointList.append((down, point[1]))
        for right in range(point[1], limitC-1):
            pointList.append((limitR-1, right))
        for up in range(limitR-1, point[0], -1):
            pointList.append((up, limitC-1))
        for left in range(limitC-1, point[1], -1):
            pointList.append((point[0], left))
        limitR, limitC = (limitR-1, limitC-1)
        circuitList.append(pointList)
    return circuitList


def rotateCircuit(givenList, rotateCount):
    result = []
    for eachCircuit in givenList:
        splitPoint = len(eachCircuit) - rotateCount % len(eachCircuit)
        rotatedCircuit = eachCircuit[splitPoint:]+eachCircuit[:splitPoint]
        result.append(rotatedCircuit)
    return result


def putPointAfterRotate(beforeList, afterList, n, m):
    emptyList = [[None for _ in range(m)] for _ in range(n)]
    for rowIdx in range(len(beforeList)):
        for colIdx in range(len(beforeList[rowIdx])):
            row, col = beforeList[rowIdx][colIdx]
            emptyList[row][col] = afterList[rowIdx][colIdx]
    return emptyList


basicCircuitSet = makeCircuitSet(N, M)
rotatedCircuitList = rotateCircuit(basicCircuitSet, R)
rotatedIndexList = putPointAfterRotate(
    basicCircuitSet, rotatedCircuitList, N, M)
for i in range(N):
    eachRow = []
    for j in range(M):
        row, col = rotatedIndexList[i][j]
        eachRow.append(originArray[row][col])
    print(*eachRow)
profile
프론트엔드 기술 학습 및 공유를 활발하게 하기 위해 노력합니다.

0개의 댓글

관련 채용 정보