-
[백준] 16926번: 배열 돌리기1(Python)Algorithm PS👩🏻💻/Implementation 2023. 5. 10. 13:28
문제
https://www.acmicpc.net/problem/16926
16926번: 배열 돌리기 1
크기가 N×M인 배열이 있을 때, 배열을 돌려보려고 한다. 배열은 다음과 같이 반시계 방향으로 돌려야 한다. A[1][1] ← A[1][2] ← A[1][3] ← A[1][4] ← A[1][5] ↓ ↑ A[2][1] A[2][2] ← A[2][3] ← A[2][4] A[2][5]
www.acmicpc.net
문제 풀이
- 회전하는 행렬의 인덱스들을 1차원 배열로 뽑아 놓는다.(반시계방향으로)
- ex.
n, m, r = 2, 3, 2 array = [[1, 2, 3], [4, 5, 6]] [(0, 0), (1, 0), (1, 1), (1, 2), (0, 2), (0, 1)] #위치 인덱스를 담은 배열
- 회전수 만큼 더해준 위치의 원소는 이동된 위치를 나타낸다.
- ex. (0+R) => 2 #R: 2
- array[0][0] 원소는 2번째 위치인 (1,1)로 이동한다.
코드
from collections import deque import sys input = sys.stdin.readline n, m, r = map(int, input().split()) array = [] #input 배열 for _ in range(n): array.append(list(map(int, input().split()))) result = [[0] * m for _ in range(n)] #결과 담는 배열 # 시작점만 주 대각선으로 잡기 row = min(n, m) // 2 start = deque([(i, i) for i in range(row)]) indices = [] #회전하는 행렬의 인덱스를 담는 배열 dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] while start: temp = [] x, y = start.popleft() for i in range(4): if i % 2 == 0: for j in range(n-1): temp.append((x, y)) x += dx[i] y += dy[i] else: for j in range(m-1): temp.append((x, y)) x += dx[i] y += dy[i] indices.append(temp) n -= 2 m -= 2 for i in range(len(indices)): length = len(indices[i]) for j in range(length): x, y = indices[i][j] nx, ny = indices[i][(j+r) % length] result[nx][ny] = array[x][y] for r in result: print(*r)
'Algorithm PS👩🏻💻 > Implementation' 카테고리의 다른 글
[백준]14500번: 테트로미노(Python) (0) 2023.08.11 [백준] 2469번: 사다리 타기(Python) (0) 2023.06.23 [프로그래머스] 2016년(Python) (0) 2023.05.23 [백준] 14719번: 빗물 (Python) (0) 2023.05.14 [백준] 17276번: 배열 돌리기 (Python) (1) 2023.05.08