題目:輸入一個(gè)矩陣拼余,按照從外向里以順時(shí)針的順序依次打印出每一個(gè)數(shù)字邮绿,例如,如果輸入如下矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數(shù)字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
(給的第一個(gè)數(shù)組是第一行误甚,第二個(gè)數(shù)組是第二行宪萄,以前在理解數(shù)組的時(shí)候記成第一個(gè)數(shù)組時(shí)第一列了,自己多注意一點(diǎn))
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> array = new ArrayList<Integer>();
if(matrix.length == 0){
return null;
}
int row = matrix.length;
int col = matrix[0].length;
int top = 0, bottom = row - 1, left = 0, right = col -1;
while((top <= bottom) && (left <= right)){
for(int i = left ; i <= right; i++){
array.add(matrix[top][i]);
}
top++;
for(int i = top; i <= bottom; i++){
array.add(matrix[i][right]);
}
right--;
if(top <= bottom){
for(int i = right; i >= left; i--){
array.add(matrix[bottom][i]);
}
bottom--;
}
if(left <= right){
for(int i = bottom; i >= top; i--){
array.add(matrix[i][left]);
}
left++;
}
}
return array;
}
}
大致的思路就是使用四個(gè)數(shù)值分別表示遍歷過(guò)后各個(gè)方向的位置屎债,后面的兩個(gè)判斷條件要謹(jǐn)記,因?yàn)橛锌赡芮懊娴牟僮鞯倪M(jìn)行之后豎向或者橫向的元素已經(jīng)遍歷過(guò)了仅政。