[코드트리: 격자 숫자 놀이]

아빠는 외계연·2023년 9월 22일
0

CodingTest

목록 보기
14/18

url : https://www.codetree.ai/training-field/frequent-problems/problems/matrix-number-play/description?page=1&pageSize=20&order=tier
Level : Gold 4
유형 : simulation

r,c,k = map(int, input().split())
A = []
for i in range(3):
    A.append(list(map(int, input().split())))

# 횟수 계산
def calculate(list_):
    dict_ = dict()
    for li in list_:
        if li == 0: continue
        if li in dict_:
            cnt = dict_[li]
            dict_[li] = cnt + 1
        else:
            dict_[li] = 1
    return dict_
# 0으로 채우기
def fill_zero(tot, max_):
    result = []
    for t in tot:
        while len(t) < max_:
            t.append(0)
        result.append(t)
    return result
# 행 계산
def column():
    max_ = -1
    tot = []
    for a in A:
        dict_ = calculate(a)
        ans = []
        for d in dict_:
            ans.append([d, dict_[d]])
        ans.sort(key = lambda x: (x[1], x[0]))
        tmp = []
        for an in ans:
            a,b = an
            tmp.append(a)
            tmp.append(b)
        if len(tmp) > 100:
            tmp = tmp[:100]
        tot.append(tmp)
        max_ = max(max_, len(tmp))
    fill_zero(tot, max_)
    return tot

# 열 계산
def row():
    max_ = -1
    tot = []
    for a in map(list, zip(*A)):
        dict_ = calculate(a)
        ans = []
        for d in dict_:
            ans.append([d, dict_[d]])
        ans.sort(key = lambda x: (x[1], x[0]))
        tmp = []
        for an in ans:
            a,b = an
            tmp.append(a)
            tmp.append(b)
        if len(tmp) > 100:
            tmp = tmp[:100]
        tot.append(tmp)
        max_ = max(max_, len(tmp))
    fill_zero(tot, max_)
    return list(map(list, zip(*tot)))

cnt = 0
while True:
    if c <= len(A[0]) and r <= len(A):
        if k == A[r-1][c-1]:
            print(cnt)
            break
    cnt += 1
    if cnt > 100:
        print(-1)
        break
    if len(A) >= len(A[0]):
        A = column()
    else:
        A = row()

조건 체크 :
1. 행(column) >= 열(row) 일 경우

  • 모든 행에 대해 정렬
    • 출현 빈도수, 작은 숫자 대로 정렬(오름차순)
    • [숫자/빈도수] 형태로 출력
    • 남은 칸 수는 0으로 채우기
  1. 행(column) < 열(row) 일 경우
  • 모든 열에 대해 위와 같이 정렬
  1. 100개가 max 행/열 길이
  2. 답이 100초를 초과하거나 목표 숫자에 도달하는 것이 불가 => -1 출력

구해야하는 값 : A[r][c] 값이 k가 되기 위한 최소 시간 출력

과정

  1. for문을 돌면서 A[r][c]값이 k와 일치하는지 확인
  2. 행과 열의 길이를 비교하고, 각각의 row(), column()함수 호출
  3. 각 row(), column()문
    • dictionary를 이용해서 출현횟수 계산
    • 빈도수, 크기 순으로 정렬하여 리스트에 append
    • 각 리스트의 max값을 구한 후 fill_zero라는 0을 채워주는 함수 호출
    • 체크할 점 : list(map(list, zip(*arr))) -> 행과 열을 바꿔준다.

생각해봐야할 점

항상 이런문제를 풀때 헷깔리는 것이 열과 행은 0부터 시작하는 데, 주어지는 값은 1부터 시작을 해서 범위체크랑 값을 출력할 때 에러가 난다.
-> 해결 : 주어지는 값을 1씩 빼고, 길이는 꼭 길이끼리 비교하기

profile
Backend Developer

0개의 댓글