54. Spiral Matrix - python3

54. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

My Answer 1: Wrong Answer (9 / 22 test cases passed.)

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        R = len(matrix)-1
        C = len(matrix[0])-1
        
        result = []
        
        r, c = 0, 0
        oddeven = 0
        
        while R != 0 and C != 0:
            if oddeven:     # even
                for j in range(C, c-1, -1):
                    result.append(matrix[R][j])
                R -= 1
                for i in range(R, r-1, -1):
                    result.append(matrix[i][c])
                c += 1
                oddeven = 0
            else:           # odd
                for j in range(c, C+1):
                    result.append(matrix[r][j])
                r += 1
                for i in range(r, R+1):
                    result.append(matrix[i][C])
                C -= 1
                oddeven = 1
            print(R, C, r, c)
        
        return result

이거.. 예시 그림대로 append 하도록 해보려 했는데 생각보다 잘 안됨..ㅎ

Solution 1: Runtime: 28 ms - 84.75% / Memory Usage: 14.3 MB - 62.29%

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        
        if len(matrix) == 0:
            return res
        
        row_begin = 0
        col_begin = 0
        row_end = len(matrix)-1 
        col_end = len(matrix[0])-1
        
        while (row_begin <= row_end and col_begin <= col_end):
            for i in range(col_begin,col_end+1):
                res.append(matrix[row_begin][i])
            row_begin += 1
            
            for i in range(row_begin,row_end+1):
                res.append(matrix[i][col_end])
            col_end -= 1
            
            if (row_begin <= row_end):
                for i in range(col_end,col_begin-1,-1):
                    res.append(matrix[row_end][i])
                row_end -= 1
                
            if (col_begin <= col_end):
                for i in range(row_end,row_begin-1,-1):
                    res.append(matrix[i][col_begin])
                col_begin += 1
                
        return res

나의 생각과 가장 일치한 솔루션...

row, col 의 begin 과 end 를 지정해서 돌때마다 값의 변화를 줌
저렇게 규칙을 발견해서 했어야 했는데....

좋은 웹페이지 즐겨찾기