class Test54 { class Solution { fun spiralOrder(matrix: Array): List { val column = matrix[0].size val row = matrix.size val result = MutableList(column * row) { 0 } var read = 0 var i = 0 var j = 0 var direction = 0 // →0 ↓1 ←2 ↑3 var round = 0 while (read != column * row){ result[read] = matrix[i][j] read++ // check boundary if ((direction == 0 || direction == 1 ) && j + 1 + round == column){ // at rightmost if (i - round == 0){ //right up direction = 1 } if (i + 1 + round == row){ direction = 2 } } else if ((direction == 2 || direction == 3 ) &&j - round == 0){ // left if (i + 1 + round == row){ direction = 3 } if (i - round -1 == 0){ direction = 0 round ++ } } // move pointer when (direction){ 0 -> j++ 1 -> i++ 2 -> j-- 3 -> i-- } } return result } } fun test(){ val solution = Solution() println(solution.spiralOrder(arrayOf(intArrayOf(1,2,3), intArrayOf(4,5,6), intArrayOf(7,8,9)))) println(solution.spiralOrder(arrayOf(intArrayOf(1,2,3,4), intArrayOf(5,6,7,8), intArrayOf(9,10,11,12)))) } }