剑指Offer20题顺时针打印矩阵(欢迎批评指正)Java版

时间:2021-09-23 14:40:17

主要的改动就是添加了一个flag.原版的在columns=4 ,rows =3的时候多打印了11。现在的改动不知道对不对。
package test;public class PrintMatrixInCircle {public void printMatrixClockwisely(int[][] numbers, int columns, int rows){if(numbers == null || columns<=0 || rows <= 0)return;int start = 0;boolean flag = true;while((columns>start*2 || rows> start*2)&&flag){flag = printMatrixInCircle(numbers, columns, rows, start, flag);++start;}}public boolean printMatrixInCircle(int[][] numbers, int columns, int rows, int start,boolean flag){int endX = columns - 1 - start;int endY = rows - 1 - start;if(start<=endX){for(int i=start; i<=endX; ++i){int number = numbers[start][i];System.out.print(number+" ");}System.out.println();}else{flag = false;}if(start< endY){for(int i=start+1; i<=endY; ++i){int number = numbers[i][endX];System.out.print(number+" ");}System.out.println();}else{flag = false;}if(start<endX && start<endY){for(int i=endX-1; i>=start; --i){int number = numbers[endY][i];System.out.print(number+" ");}System.out.println();}else{flag = false;}if(start<endX && start<endY-1){for(int i=endY-1; i>=start+1; --i){int number = numbers[i][start];System.out.print(number+" ");}System.out.println();}else{flag = false;}return flag;}public static void main(String[] args) {// TODO Auto-generated method stub//int[][] numbers = {{1,2,3,4},// {5,6,7,8},// {9,10,11,12},// {13,14,15,16}};//int[][] numbers = {{1,2,3,4,17},// 11 was printed two//{5,6,7,8,18},//{9,10,11,12,19},//{13,14,15,16,20}};//int[][] numbers = {{1,2,3},//{5,6,7},//{9,10,11},//{13,14,15},//{16,17,18}};int[][] numbers = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};PrintMatrixInCircle printMatrixInCircle = new PrintMatrixInCircle();printMatrixInCircle.printMatrixClockwisely(numbers, 4, 3);}}