我有一些代码(参考这个例子)来遍历一个矩阵,从左上角开始顺时针方向。我想基于此创建三种新方法:
- 一个从左上角开始逆时针方向
- 一个从中间开始顺时针方向
- 一个从中间开始逆时针方向
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());
}