publicclassSolution{publicIList<int> SpiralOrder(int[][] matrix) {List<int> result =new();if (matrix.Length>0) {int top =0, bottom =matrix.Length-1;int left =0, right =matrix[0].Length-1;int dir =0; // 0: right, 1: down, 2: left, 3: upwhile (top <= bottom && left <= right) {if (dir ==0) { // Move rightfor (int i = left; i <= right; i++) result.Add(matrix[top][i]); top++; }elseif (dir ==1) { // Move downfor (int i = top; i <= bottom; i++) result.Add(matrix[i][right]); right--; }elseif (dir ==2) { // Move leftfor (int i = right; i >= left; i--) result.Add(matrix[bottom][i]); bottom--; }elseif (dir ==3) { // Move upfor (int i = bottom; i >= top; i--) result.Add(matrix[i][left]); left++; } dir = (dir +1) %4; // Change direction } }return result; }}
The time complexity is still O(mn), and the space complexity is O(1) excluding the output. This is because it does not use any additional data structures whose size depends on the input. The output size is O(mn), as it includes all elements of the matrix. This version of the method