一个面试题,顺时针打印矩阵
总体思路是:从外圈到内圈一圈一圈打印。
在条件判断上可以变化。
code:
package com.zxy.exercise;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Print matrix
int[][] matrix = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11,12,13,14,15}};
printMatrixClockwise(matrix, 3, 5);
}
//一圈一圈打印
public static void printMatrixClockwise(int[][] matrix, int rows, int cols){
int counts = rows * cols;
int count = 0;
int circle = 0;
int i = 0, j = 0;
//每打印一个数,count++
while(count < counts){
while(j <= cols - 1 - circle && count < counts){
System.out.print(matrix[i][j] + " ");
j++;
count++;
}
j--;
i++;
while(i <= rows - 1 - circle && count < counts){
System.out.print(matrix[i][j] + " ");
i++;
count++;
}
i--;
j--;
while(j >= circle && count < counts){
System.out.print(matrix[i][j] + " ");
j--;
count++;
}
j++;
i--;
circle++;
while(i >= circle && count < counts){
System.out.print(matrix[i][j] + " ");
i--;
count++;
}
i++;
j++;
}
}
}