剑指offer有一道关于顺时针打印矩阵的面试题,感觉挺有意思的,题意很简单,输入一个矩阵,顺时针打印每个数字。
例如输入以下矩阵
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 。本体的关键是要把握好边界条件,每次从左上角的开始打印。
package sxd.learn.java.questions;
public class PrintMatrix {
private int r_upper_threshold;
private int c_upper_threshold;
private int r_lower_threshold;
private int c_lower_threshold;
public static void main(String[] args) {
new PrintMatrix().run();
}
public void run(){
int[][] matrix1 = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int[][] matrix2 = {
{1, 2, 3, 4},
{2, 3, 4, 5},
{5, 6, 7, 8},
};
int[][] matrix3 = {
{1}, {2}, {3}, {4}
};
int[][] matrix4 = {
{1, 2},
{5, 6},
{3, 4},
{7, 8},
};
int[][] matrix5 = {
{1, 2, 3, 4}
};
printMatirxClockwisely(matrix5, 1, 4);
}
public void printMatirxClockwisely(int[][] matrix, int rows, int columns) {
r_upper_threshold = rows;
c_upper_threshold = columns;
r_lower_threshold = -1;
c_lower_threshold = -1;
int startRows = 0;
int startCols = 0;
while (startRows < r_upper_threshold && startCols < c_upper_threshold) {
printMatrixInCircle(matrix, startRows, startCols);
r_lower_threshold++;
c_lower_threshold++;
r_upper_threshold--;
c_upper_threshold--;
startRows++;
startCols++;
}
}
private void printMatrixInCircle(int[][] matrix ,int r, int c){
while (c < c_upper_threshold){
System.out.print(matrix[r][c] + " ");
c++;
}
c--;
r++;
while (r < r_upper_threshold) {
System.out.print(matrix[r][c] + " ");
r++;
}
r--;
c--;
while (c > c_lower_threshold && r != r_lower_threshold + 1) {
System.out.print(matrix[r][c] + " ");
c--;
}
c++;
r--;
while (r > r_lower_threshold + 1 && c != c_upper_threshold - 1) {
System.out.print(matrix[r][c] + " ");
r--;
}
}
}