题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
代码如下: 需要注意的是每次打印后判断边界的情况。 public static ArrayList printMatrix1(int [][] matrix) { int left = 0; int right = matrix[0].length-1; int top = 0; int bottom = matrix.length-1;
ArrayList arrayList = new ArrayList();
while (true){
//->
for (int i = left; i < right+1; i++) {
arrayList.add(matrix[top][i]);
}
top++;
if( top > bottom ){
break;
}
//向下
for (int i = top; i < bottom+1; i++) {
arrayList.add(matrix[i][right]);
}
right--;
if( left > right ){
break;
}
//<-
for (int i = right; i > left-1; i--) {
arrayList.add(matrix[bottom][i]);
}
bottom--;
if( top > bottom ){
break;
}
//向上
for (int i = bottom; i >top-1 ; i--) {
arrayList.add(matrix[i][left]);
}
left++;
if( left > right ){
break;
}
}
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(" "+arrayList.get(i));
}
return arrayList;
}