문제풀이/구현

● [파이썬] [구현] 백준 17140 이차원 배열과 연산

승무_ 2023. 3. 31. 18:32

문제

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

 

17140번: 이차원 배열과 연산

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

www.acmicpc.net

코드

from copy import deepcopy

r,c,k=map(int, input().split())
array=[list(map(int, input().split())) for _ in range(3)]

def calR():
    for i in range(len(array)):
        countNumber = [0] * 101
        for j in array[i]:
            countNumber[j]+=1
        temp=[]
        # [3, 1, 1] -> [3, 1, 1, 2]
        for j in range(1,len(countNumber)):
            if countNumber[j]>0:
               temp.append([j,countNumber[j]])
        #조건이 두개일 때 정렬
        temp.sort(key = lambda x : (x[1],x[0]))
        array[i].clear()
        for key,value in temp:
            if len(array[i])<99:
                array[i].append(key)
            if len(array[i]) < 99:
                array[i].append(value)
    maxlen=0
    # 가장 길이가 긴것에 맞추어 0 채우기
    for i in range(len(array)):
        maxlen=max(maxlen, len(array[i]))
    for i in range(len(array)):
        while len(array[i])<maxlen:
            array[i].append(0)

def calC():
    global array
    # calR과 똑같이 계산하고 맨 마지막에 90도 회전
    # temp0 은 90도 회전하기 전 배열
    temp0=[]
    for i in range(len(array[0])):
        countNumber = [0] * 101
        for j in range(len(array)):
            countNumber[array[j][i]]+=1
        temp=[]
        for j in range(1,len(countNumber)):
            if countNumber[j]>0:
               temp.append([j,countNumber[j]])
        temp.sort(key = lambda x : (x[1],x[0]))
        # 100개가 넘어가는 경우 제외해야 하기 때문에 이를 위한 임시 배열
        temp100=[]
        for key,value in temp:
            if len(temp100)<99:
                temp100.append(key)
            if len(temp100)<99:
                temp100.append(value)
        temp0.append(temp100)
    maxlen=0
    for i in range(len(temp0)):
        maxlen=max(maxlen, len(temp0[i]))
    for i in range(len(temp0)):
        while len(temp0[i])<maxlen:
            temp0[i].append(0)
    # 90도 회전 시키기
    temp90=[[0]*len(temp0) for _ in range(len(temp0[0]))]
    for i in range(len(temp0)):
        for j in range(len(temp0[0])):
            temp90[j][i]=temp0[i][j]
    array.clear()
    array=deepcopy(temp90)

# 첫번째 if 예외 처리 조심
if len(array)>=r and len(array[0])>=c:
    if array[r-1][c-1]==k:
        print(0)
        exit(0)

for i in range(1,101):
    if len(array)>=len(array[0]):
        calR()
    else:
        calC()
    if len(array)<r or len(array[0])<c:
        continue
    if array[r-1][c-1]==k:
        print(i)
        exit(0)
print(-1)