标签:stat 题目 while 示例 代码 res 面试 matrix 面试题
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
import java.util.ArrayList;
import java.util.List;
public class Offer20 {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10,11,12},
{13,14,15,16}
};
Offer20 testObj = new Offer20();
List<Integer> res = testObj.printMatrix(matrix);
System.out.println(res);
}
public List<Integer> printMatrix(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int rowLeft = 0;
int rowRight = matrix.length - 1;
int colLeft = 0;
int colRight = matrix[0].length - 1;
while (rowLeft <= rowRight && colLeft <= colRight) {
//先向右
for (int i = rowLeft; i <= rowRight; i++) {
res.add(matrix[rowLeft][i]);
}
//向下
for (int i = rowLeft + 1; i <= rowRight; i++) {
res.add(matrix[i][rowRight]);
}
//防止打印同一行
if (rowLeft != rowRight) {
//向左
for (int i = rowRight - 1; i >= rowLeft; i--) {
res.add(matrix[rowRight][i]);
}
}
if (colLeft != colRight) {
//向上
for (int i = rowRight - 1; i > rowLeft; i--) {
res.add(matrix[i][colLeft]);
}
}
rowLeft++;
rowRight--;
colLeft++;
colRight--;
}
return res;
}
}
标签:stat 题目 while 示例 代码 res 面试 matrix 面试题
原文地址:https://www.cnblogs.com/ITxiaolei/p/13167007.html