Possible duplicate - print spiral order matrix
I am trying to solve a question to print a matrix in a spiral manner. For eg, if Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
, Output: [1,2,3,6,9,8,7,4,5]
Here is my algorithm. It works as expected except I see 4 getting printed twice, and I really can't seem to figure out why.
public static void main(String[] args) {
SprialMatrix spm = new SprialMatrix();
int[][] inputArr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
int col = inputArr[0].length;
int row = inputArr.length;
spm.buildOutputArr(inputArr, row, col);
}
public void buildOutputArr(int[][] inputArr, int row, int column) {
int top = 0, bottom = row - 1, left = 0, right = column - 1;
int dir = 0;
while (top <= bottom && left <= right) {
// dir = 0, go from left to right
if (dir == 0) {
for (int i = left; i <= right; i++) {
System.out.println(inputArr[top][i]);
}
}
else if (dir == 1) {
// dir = 1, go from top to bottom
top = top + 1;
for (int i = top; i <= bottom; i++) {
System.out.println(inputArr[i][right]);
}
} else if (dir == 2) {
// dir = 2, go from right to left
right = right - 1;
for (int i = right; i >= left; i--) {
System.out.println(inputArr[bottom][i]);
}
} else if (dir == 3) {
// dir = 3, go from bottom to up
bottom = bottom - 1;
for (int i = bottom; i >= top; i--) {
System.out.println(inputArr[i][left]);
}
}
dir = (dir + 1) % 4;
}
}
I can't seem to figure out what the issue is in my code. What can I try next?