본문 바로가기

CodingTest/SW Expert Academy

[ SW Expert Academy ] Magnetic

아.. 다 온 것 같은데 정답이랑 1-2개씩 답이 다르네 ㅠㅜ 뭐지...

from collections import deque
for tc in range(1, 11):
    n = int(input())
    result = 0
    table = []
    magnetic = deque([])
    for i in range(100):
        row = list(map(int, input().split()))
        for j in range(100):
            if row[j] != 0:
                magnetic.append((i, j))
        table.append(row)

    prev_len = 0
    while prev_len != len(magnetic):
        prev_len = len(magnetic)

        for i in range(len(magnetic)):
            x, y,  = magnetic.popleft()
            if table[x][y] == 1:
                if x + 1 < 100 and table[x+1][y] != 2:
                    table[x][y] = 0
                    x += 1
                    table[x][y] = 1
                    magnetic.append((x, y))
                elif x + 1 >= 100:
                    table[x][y] = 0


            elif table[x][y] == 2:
                if x-1 >= 0 and table[x-1][y] != 1:
                    table[x][y] = 0
                    x -= 1
                    table[x][y] = 2
                    magnetic.append((x, y))
                elif x - 1 < 0:
                    table[x][y] = 0

    for i in range(100):
        for j in range(100):
            if table[i][j] == 1:
                k = i
                while k < 100 and table[k][j] != 2:
                    table[k][j] = 0
                    k += 1
                if k != 100: table[k][j] = 0
                result += 1

    print("#{} {}".format(tc, result))

 

일단 구현 자체도 미스난 것 같고.. 

( 마지막에 카운팅에서 실패인 듯)

 

구현을 직접 하지 않고 그냥 규칙만 찾아 적용하면 되는 문제란다..

 

와.. 이걸 스택으로 해결하면 되었을 줄이야 ㅠㅜ

 

1차 제출 PASS

 

for tc in range(1, 3):
    n = int(input())
    result = 0
    table = [list(map(int, input().split())) for _ in range(n)]
    for j in range(n):
        r = 0
        stack = []

        while r < n:
            if not stack and table[r][j] == 1:
                stack.append(1)
            elif stack and table[r][j] == 2:
                result += stack.pop()
            r += 1

    print("#{} {}".format(tc, result))