Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
.
Analysis:
Try to follow the steps from left to right, to bottom to left to up.
Note to consider the situations where row/col = 1
Time complexity: O(mn)
Space complexity: O(1)
The code is below:
public class Solution {
public List spiralOrder(int[][] matrix) {
// O(mn)
List result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int row = matrix.length;
int col = matrix[0].length;
int x = 0;
int y = 0;
while (row > 0 && col > 0) {
// Only one row
if (row == 1) {
for (int i = 0; i < col; i++) {
result.add(matrix[x][y++]);
}
break;
}
// Only one col
if (col == 1) {
for (int i = 0; i < row; i++) {
result.add(matrix[x++][y]);
}
break;
}
// Move from top to right
for (int i = 0; i < col - 1; i++) {
result.add(matrix[x][y++]);
}
// Move from right to bottom
for (int i = 0; i < row - 1; i++) {
result.add(matrix[x++][y]);
}
// Move from bottem to lef
for (int i = 0; i < col - 1; i++) {
result.add(matrix[x][y--]);
}
// Move from left to top
for (int i = 0; i < row - 1; i++) {
result.add(matrix[x--][y]);
}
row -= 2;
col -= 2;
x++;
y++;
}
return result;
}
}
Followup:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Analysis:
Similar to the first question.
Time complexity: O(mn)
Space complexity: O(1)
Code is below:
public class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int num = 1;
int x = 0;
int y = 0;
int row = n;
int col = n;
while (num <= n * n) {
// one row/col
if (row == 1 || col == 1) {
matrix[x][y] = num;
break;
}
// top to right
for (int i = 0; i < col - 1; i++, num++) {
matrix[x][y++] = num;
}
// right to bottom
for (int i = 0; i < row - 1; i++, num++) {
matrix[x++][y] = num;
}
// bottom to left
for (int i = 0; i < col - 1; i++, num++) {
matrix[x][y--] = num;
}
// left to top
for (int i = 0; i < row - 1; i++, num++) {
matrix[x--][y] = num;
}
row -= 2;
col -= 2;
x++;
y++;
}
return matrix;
}
}