题意:顺时针打印出矩阵的所有元素
思路:看代码。
代码:
package MianShiTi_20;
public class MianShiTi_20 {
public static void printMatrixClockwisely(int[][] numbers) {
int rows = numbers.length;
int cols = numbers[0].length;
//以start为索引值
int start = 0;
//在满足rows > 2*start && cols > 2*start的时候,才能打印出矩阵。
while (rows > 2*start && cols > 2*start) {
printMatrix(numbers , start);
start++;
}
}
public static void printMatrix(int[][] numbers , int start) {
int rows = numbers.length;
int cols = numbers[0].length;
int endX = cols - 1 - start;
int endY = rows - 1 - start;
//从左到右打印一行
for (int i = 0; i <= endX; i++) {
int number = numbers[start][i];
printNumber(number);
}
//从上到下打印一行
if(start < endY){
for (int i = start + 1; i<= endY ; i++) {
int number = numbers[i][endY];
printNumber(number);
}
}
//从右到左打印一行
if(start < endX){
for(int i = endX - 1; i >=start ; i--){
int number = numbers[endX][i];
printNumber(number);
}
}
//从下到上打印一行
if(start < endX && start < endY - 1){
for(int i = endY - 1; i >= start +1;--i){
int number = numbers[i][start];
printNumber(number);
}
}
}
public static void printNumber(int number) {
System.out.print(number+" ");
}
public static void main(String[] args) {
int[][] numbers = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
MianShiTi_20 test = new MianShiTi_20();
test.printMatrixClockwisely(numbers);
}
}