공부하고 기록하는, 경제학과 출신 개발자의 노트

프로그래밍/코딩테스트 문제풀이

[Python] 백준 17140. 이차원 배열과 연산

inspirit941 2020. 1. 29. 10:49
반응형

https://www.acmicpc.net/problem/17140

 

17140번: 이차원 배열과 연산

첫째 줄에 r, c, k가 주어진다. (1 ≤ r, c, k ≤ 100) 둘째 줄부터 3개의 줄에 배열 A에 들어있는 수가 주어진다. 배열 A에 들어있는 수는 100보다 작거나 같은 자연수이다.

www.acmicpc.net

시뮬레이션 문제.

c연산을 수행할 때 row와 column을 바꾸는 transpose 연산을 해줘야 하는데, python에서는 map과 zip함수를 써서 쉽게 변형할 수 있다.

 

 

import sys
from collections import Counter
r, c, k = map(int, sys.stdin.readline().split())
maps = []
for _ in range(3):
temp = list(map(int, sys.stdin.readline().split()))
maps.append(temp)
time = 0
find = False
while time <= 100:
if r <= len(maps) and c <= len(maps[0]) and maps[r-1][c-1] == k:
print(time)
find = True
break
time += 1
max_col = 0
next_maps = []
# R연산
if len(maps) >= len(maps[0]):
for rows in maps:
next_row = []
count_table = sorted(list(Counter(rows).items()), key = lambda x: (x[1], x[0]))
for num, cnt in count_table:
if num == 0:
continue
next_row.append(num)
next_row.append(cnt)
max_col = max(max_col, len(next_row))
next_maps.append(next_row)
# 가장 긴 row 길이에 맞게 0 개수 채우기
for rows in next_maps:
if len(rows) < max_col:
for _ in range(max_col - len(rows)):
rows.append(0)
maps = next_maps
continue
# c연산
elif len(maps) < len(maps[0]):
# 2차원 list transpose
maps = list(map(list, zip(*maps)))
for rows in maps:
next_row = []
count_table = sorted(list(Counter(rows).items()), key = lambda x: (x[1], x[0]))
for num, cnt in count_table:
if num == 0:
continue
next_row.append(num)
next_row.append(cnt)
max_col = max(max_col, len(next_row))
next_maps.append(next_row)
# 가장 긴 row 길이에 맞게 0 개수 채우기
for rows in next_maps:
if len(rows) < max_col:
for _ in range(max_col - len(rows)):
rows.append(0)
# c연산 결과에 맞게 다시 transpose
maps = list(map(list, zip(*next_maps)))
continue
if not find:
print(-1)
반응형