I have some code (following this example) to traverse a matrix starting from the upper left and going clockwise. I want to make three new methods based off of this:
- One that starts from the top left and goes counterclockwise
- One that starts from the middle and goes clockwise
- One that starts from the middle and goes counterclockwise
What do I need to change for each of these to work? I've tried reversing the counter increments and changing the start/end row/columns with no success.
public static void traverseSpiral(int[][] matrix) {
if(matrix.length == 0|| matrix[0].length == 0) {
return;
}
StringBuffer stringBuffer = new StringBuffer();
int counter = matrix.length * matrix[0].length;
int startRow = 0;
int endRow = matrix.length-1;
int startCol = 0;
int endCol = matrix[0].length-1;
boolean moveCol = true;
boolean leftToRight = true;
boolean upDown = true;
while(counter>0) {
if(moveCol) {
if(leftToRight) {
/* printing entire row left to right */
for(int i = startCol; i <= endCol ; i++){
stringBuffer.append(matrix[startRow][i]);
counter--;
}
leftToRight = false;
moveCol = false;
startRow++;
}
else{
/* printing entire row right to left */
for(int i = endCol ; i >= startCol ; i--){
stringBuffer.append(matrix[endRow][i]);
counter--;
}
leftToRight = true;
moveCol = false;
endRow--;
}
}
else
{
if(upDown){
/* printing column up down */
for(int i = startRow ; i <= endRow ; i++){
stringBuffer.append(matrix[i][endCol]);
counter--;
}
upDown = false;
moveCol = true;
endCol--;
}
else
{
/* printing entire col down up */
for(int i = endRow ; i >= startRow ; i--){
stringBuffer.append(matrix[i][startCol]);
counter--;
}
upDown = true;
moveCol = true;
startCol++;
}
}
}
System.out.println(stringBuffer.toString());
}