题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每个数字。
思路:先分析每一圈的起点,我们发现左上角的x和y是一样的,并且依次递增;接着分析每一圈怎么画出来,先画从左到右,接着从上到下,接着从右到左,最后从下到上。
解决方案:
public class Question29 {
public static void printMatrixInCircle(int[][] numbers, int colums, int rows, int start){
int endX = colums -1 -start;
int endY = rows -1 -start;
// 从左到右打印一行
for (int i=start; i<=endX; i++){
int number = numbers[i][start];
System.out.println(number);
}
// 从上到下打印一列
if (start < endY){
for (int i=start+1; i<=endY; i++){
int number = numbers[endX][i];
System.out.println(number);
}
}
// 从右到左打印一行
if (start < endX && start < endY){
for (int i=endX-1; i>=start; i--){
int number = numbers[i][endY];
System.out.println(number);
}
}
// 从下到上打印一列
if (start < endY-1 && start < endX){
for (int i=endY-1; i>=start+1; i--){
int number = numbers[start][i];
System.out.println(number);
}
}
}
public static void printMatrixClockwisely(int[][] numbers, int columns, int rows){
if (numbers == null || columns < 0 || rows < 0) return;
int start = 0;
while (columns > start * 2 && rows > start * 2){
printMatrixInCircle(numbers, columns, rows, start);
++ start;
}
}
public static void main(String[] args) {
int[][] numbers= new int[][]{
{1,3,5,7,9},{2,4,6,8,10}
};
System.out.println("test " + numbers[1][0]);
printMatrixClockwisely(numbers, numbers.length, numbers[0].length);
}
}
网友评论