Java 实现打印螺旋矩阵

输入一个矩阵,以顺时针的顺序依次打印出每一个数字

例如,如果输入如下矩阵: 

1    2    3 

8    9    4

7     6    5

则依次打印出数字1,2,3,4,5,6,7,8,9

代码

    private static List<Integer> getMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return null;
        }
        int row = matrix.length, col = matrix[0].length;
        //存放结果
        List<Integer> result = new ArrayList<>(row * col);
        // 其实列和结束列
        int startCol = 0, endCol = col - 1;
        // 其实行和结束行
        int startRow = 0, endRow = row - 1;
        while (startCol <= endCol && startRow <= endRow) {
            // 1. 遍历startRow行的各列数据,从左到右,遍历结束,对startRow+1,表示该行数据已经遍历过
            if (startCol <= endCol && startRow <= endRow) {
                for (int i = startCol; i <= endCol; i++) {
                    result.add(matrix[startRow][i]);
                }
                ++startRow;
            }
            // 2. 遍历endCol列的各行数据,从上到下,遍历结束,对endCol-1,表示该列数据已经遍历过
            //    因为前一步遍历startRow行后,将要从当前行的最后一列所在列开始遍历
            if (startCol <= endCol && startRow <= endRow) {
                for (int i = startRow; i <= endRow; i++) {
                    result.add(matrix[i][endCol]);
                }
                --endCol;
            }
            // 3. 遍历endRow行的各列数据,从右到左,遍历结束,对endRow-1,表示该行数据已经遍历过
            //    因为前一步遍历endCol列后,将要从当前列的最后一行所在行开始遍历
            if (startCol <= endCol && startRow <= endRow) {
                for (int i = endCol; i >= startCol; i--) {
                    result.add(matrix[endRow][i]);
                }
                --endRow;
            }
            // 4. 遍历startCol列的各行数据,从下到上,遍历结束,对startCol+1,表示该列数据已经遍历过
            //    同样,上一次之后,回到了行的最左侧,所以开始向上遍历该行所在的列
            if (startCol <= endCol && startRow <= endRow) {
                for (int i = endRow; i >= startRow; i--) {
                    result.add(matrix[i][startCol]);
                }
                ++startCol;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // 创建一个数组
        // 1  2  3
        // 8  9  4
        // 7  6  5
        int[][] matrix = {{1,2,3}, {8,9,4}, {7,6,5}};
        List<Integer> result = getMatrix(matrix);
        if (CollectionUtils.isNotEmpty(result)) {
            // 结果应是: 1 2 3 4 5 6 7 8 9
            for(Integer i : result) {
                System.out.print(i + " ");
            }
        }
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值