from utils.matrix import Matrix

class Solution:
    def traverse(self, matrix):
        """
        :type matrix: Matrix
        :rtype: List[int]
        """
        if not matrix.row_count or not matrix.col_count:
            return

        row, col = 0, 0
        d_row, d_col = -1, 1
        result = []
        for _ in range(matrix.row_count * matrix.col_count):
            result.append(matrix[row][col])
            row += d_row
            col += d_col
            if not self.is_valid_cell(row, col, matrix):
                if col == matrix.col_count:
                    col -= 1
                    row += 2
                elif row < 0:
                    row = 0
                elif row == matrix.row_count:
                    row -= 1
                    col += 2
                elif col < 0:
                    col = 0
                d_row, d_col = d_col, d_row
        return result

    def is_valid_cell(self, row, col, matrix):
        return (
            row >= 0 and row < matrix.row_count and
            col >= 0 and col < matrix.col_count
        )

# matrix = Matrix([[1,2,3],[4,5,6]])
matrix = Matrix([[1,2,3],[4,5,6], [7,8,9]])
print(matrix)
solution = Solution()
print(solution.traverse(matrix))