1.簡述:
描述
輸入一個矩陣,按照從外向里以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣:
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
則依次打印出數字
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
數據范圍:
0 <= matrix.length <= 100
0 <= matrix[i].length?<= 100
示例1
輸入:
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
返回值:
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
示例2
輸入:
[[1,2,3,1],[4,5,6,1],[4,5,6,1]]
返回值:
[1,2,3,1,1,1,6,5,4,4,5,6]
2.代碼實現:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
//先排除特殊情況
if(matrix.length == 0) {
return res;
}
//左邊界
int left = 0;
//右邊界
int right = matrix[0].length - 1;
//上邊界
int up = 0;
//下邊界
int down = matrix.length - 1;
//直到邊界重合
while(left <= right && up <= down){
//上邊界的從左到右
for(int i = left; i <= right; i++)
res.add(matrix[up][i]);
//上邊界向下
up++;
if(up > down)
break;
//右邊界的從上到下
for(int i = up; i <= down; i++)
res.add(matrix[i][right]);
//右邊界向左
right--;
if(left > right)
break;
//下邊界的從右到左
for(int i = right; i >= left; i--)
res.add(matrix[down][i]);
//下邊界向上
down--;
if(up > down)
break;
//左邊界的從下到上
for(int i = down; i >= up; i--)
res.add(matrix[i][left]);
//左邊界向右
left++;
if(left > right)
break;
}
return res;
}
}
本文摘自 :https://blog.51cto.com/u