【刷题笔记2】螺旋矩阵

题目

用螺旋的方式打印矩阵, 比如如下的矩阵
0   1   2    3
4   5   6    7
8   9   10  11

打印顺序为: 0 1 2 3 7 11 10 9 8 4 5 6

思路

1.定义两个点分别指向矩阵左上角和右下角两个位置。
2.根据p1,p2的行和列的值将一圈分成4块,按顺序打印这4部分的值。
3.一圈打印结束后向右下角移动p1,向左上角移动p2。
4.重复2,3步骤,直到p1,p2相遇。(注意当p1,p2在同一行和同一列的时候需要单独讨论,这个时候只要单独打印一行或者一列)

图解

代码实现

public class Problem03_SpiralMatrix {

    public static void spiralMatrix(int[][] matrix) {
        //1.首先定义两个点p1,p2位置表示为matrix[r1][c1],matrix[r2][c2]
        //分别指向矩阵左上角和右下角两个位置
        int r1 = 0;
        int c1 = 0;
        int r2 = matrix.length - 1;
        int c2 = matrix[0].length - 1;
        //2.当r1 <= r2 && c1 <= c2打印结束
        while (r1 <= r2 && c1 <= c2) {
            //3.调用打印方法,一圈打印结束后向右下角移动p1,向左上角移动p2
            printEdge(matrix, r1++, c1++, r2--, c2--);
        }

    }

    public static void printEdge(int[][] matrix, int r1, int c1, int r2, int c2) {
        int tempC = c1;
        int tempR = r1;
        if (r1 == r2) { //在同一行
            while (tempC <= c2) {
                System.out.print(matrix[tempR][tempC] + " ");
                tempC++;
            }
        } else if (c1 == c2) {  //在同一列
            while (tempR <= r2) {
                System.out.print(matrix[tempR][tempC] + " ");
                tempR++;
            }
        } else {  //按顺序打印四个部分的数
            while (c2 - tempC > 0) {
                System.out.print(matrix[tempR][tempC] + " ");
                tempC++;
            }
            while (r2 - tempR > 0) {
                System.out.print(matrix[tempR][tempC] + " ");
                tempR++;
            }
            while (tempC > c1) {
                System.out.print(matrix[tempR][tempC] + " ");
                tempC--;
            }
            while (tempR > r1) {
                System.out.print(matrix[tempR][tempC] + " ");
                tempR--;
            }
        }
    }
    //测试代码
        public static void main(String[] args) {
        int[][] matrix = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
        spiralMatrix(matrix);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值