输入一个矩阵 将这个矩阵顺时针以顺时针的顺序依次打印 java实现

/**

  • 输入一个矩阵 将这个矩阵顺时针以顺时针的顺序依次打印

  • 1 2 3

  • 4 5 6 ——>1 2 3 6 9 8 7 4 5

  • 7 8 9

  • @author Administrator
    *解题的思路就是从最外层开始输出,然后一圈一圈的向内收缩输出
    */
    public class JuZhen {
    public static void main(String[] args) {
    //测试数据
    int [][]nums={{1,2,3},{4,5,6},{7,8,9}};
    int [][]nums2={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int [][]nums3={{1,2},{3,4}};
    int [][]nums4={{1}};
    int [][]nums5={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    int [][]nums6={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
    shuChu(0,0,nums6.length-1,nums6[0].length-1,nums6);
    }

    public static void shuChu(int starX,int starY,int endX,int endY,int [][]nums){

     //解决类似 7 8 9 这样的数 如果不写这个数组就会输出 7 8 9 8 7
     if(starX==endX){
     	//输出一层
     	for (int i = starY; i < endY+1; i++) {
     		System.out.print(nums[starX][i]+" ");
     	}
     	return;
     }
     if(starY==endY){
     	for (int i = starX+1; i < endX+1; i++) {
     		System.out.print(nums[i][endY]+" ");
     	}
     }
     
     //输出一层
     for (int i = starY; i < endY+1; i++) {
     	System.out.print(nums[starX][i]+" ");
     }	
     for (int i = starX+1; i < endX+1; i++) {
     	System.out.print(nums[i][endY]+" ");
     }
     for (int i = endY-1; i >=starY; i--) {
     	System.out.print(nums[endX][i]+" ");
     }
     for (int i = endX-1; i >starX; i--) {
     	System.out.print(nums[i][starY]+" ");
     }
     
     //判断此时这一个环的形态
     if(starX+1>endX-1||starY+1>endY-1){
     	//最后一个矩阵是矩形 高大于2
     	return;
     }
     if(starX==endX&&starY==endY){
     	//最后一个矩阵是的单个
     	return;
     }
     if(starX+1==endX&&starY+1==endY){
     	//最后一个矩阵是田字格
     	return;
     }
     shuChu(starX+1, starY+1, endX-1, endY-1, nums);
    

    }

}

猜你喜欢

转载自blog.csdn.net/qq_40445661/article/details/83175996