Spiral Matrix
1 min readMay 5, 2023
https://leetcode.com/problems/spiral-matrix/
Let inputMatrix
be a matrix of numRows
rows and numCols
columns.
Look carefully at the image above. Instead of following numerical order, we’ll copy the outer edges of the array, in order. Then we’ll move on to the inner edges. These edges create the spiral. Copy the edges in in the following order:
- Top row from left to right.
- Rightmost column from top to bottom.
- Bottom row from right to left.
- Leftmost column from bottom to top.
We’ll need to keep track of our edges in order to figure which row/column is next. To do that, we’ll maintain 4 indices:
topRow
- index of the the uppermost row to be copied, starting from0
and incrementing.btmRow
- index of the the lowermost row to be copied, starting fromnumRows-1
and decrementing.leftCol
- index of the leftmost column to be copied, starting from0
and incrementing.rightCol
- index of the the rightmost column to be copied, starting fromnumCols-1
and decrementing.
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList();
int row = matrix.length;
if(row ==0 )return list;
int col = matrix[0].length;
int l = 0 , r = col-1 , t = 0 , b = row-1 , d = 0;
while(l<=r && t<=b&&list.size()<=row*col){
for(int i=l;i<=r;i++){
list.add(matrix[t][i]);
}
t++;
for(int i=t;i<=b;i++){
list.add(matrix[i][r]);
}
r--;
if(t<=b){
for(int i =r;i>=l;i--){
list.add(matrix[b][i]);
}
b--;
}
if(l<=r){
for(int i = b;i>=t;i--){
list.add(matrix[i][l]);
}
l++;
}
}
return list;
}
}