We have 4 boundaries - left, right, top and bottom. We now have to loop from left to right, then top to bottom, then right to left and bottom to top. Each time, we change direction, we update respective boundary.
Also, we can run the loop in 2 ways:
1
while(left < right && top < bottom)
OR
1
while(ans.size() < m*n)
In the code below, we are using latter, but any of the conditions will work.
classSolution {
public List<Integer>spiralOrder(int[][] matrix) {
List<Integer> ans =new ArrayList<Integer> ();
if (matrix ==null|| matrix.length== 0 || matrix[0].length== 0) {
return ans;
}
int m = matrix.length;
int n = matrix[0].length;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = m - 1;
while (ans.size() < m * n) {
for (int i = left; i<= right; i++) {
ans.add(matrix[top][i]);
}
top++;
for (int i = top; i<= bottom; i++) {
ans.add(matrix[i][right]);
}
right--;
//prevent duplicate rowif (top <= bottom) {
for (int i = right; i >= left; i--) {
ans.add(matrix[bottom][i]);
}
bottom--;
}
// prevent duplicate columnif (left <= right) {
for (int i = bottom; i >= top; i--) {
ans.add(matrix[i][left]);
}
left++;
}
}
return ans;
}
}
Initially, consider the boundaries for mXn matrix (similar to previous method):
top = 0
right = n – 1
bottom = m – 1
left = 0
Also:
dir == 1, print top row
dir == 2, print right column
dir == 3, print bottom row
dir == 4, print left column
Also, initially, dir = 1
dir = 1
So, when dir == 1, we have:
1
2
3
4
5
for (int i = left; i<= right; ++i) {
print arr[top][i];
}
++top;
We must keep rotating the value of dir between 1, 2, 3, 4 as long as top ≤ bottom and left ≤ right. If you have understood the logic, you should be able to write the code easily. If you didn’t just go through the explanation once more, it is can be tricky.
classSolution {
public List<Integer>spiralOrder(int[][] matrix) {
List<Integer> ans =new ArrayList<>();
if (matrix.length== 0 || matrix[0].length== 0) {
return ans;
}
int top = 0;
int bottom = matrix.length- 1;
int left = 0;
int right = matrix[0].length- 1;
int dir = 0; // we go right, down, left, topwhile (top <= bottom && left <= right) {
switch (dir) {
case 0: // Rightfor (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++;
break;
case 1: // Downfor (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;
break;
case 2: // Leftfor (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--;
break;
case 3: // Topfor (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
dir = (dir + 1) % 4;
}
return result;
}
}