zoukankan      html  css  js  c++  java
  • 转圈打印矩阵

    给定一个整型矩阵matrix,请按照转圈的方式打印它。 例如:
    1 2 3 4
    5 6 7 8
    9 10 11 12
    13 14 15 16
    打印结果为:1,2,3,4,8,12,16,15,14,13,9, 5,6,7,11, 10
    【要求】 额外空间复杂度为O(1)。

    Code

    //coding=utf8                                                                                                         /*****************************************************
     @Author: Alex
     @Created Time : Tue 27 Aug 2019 08:48:30 AM CST
    
     @File Name: main.java
     @Blog: https://blog.csdn.net/weixin_43336281
    
     ****************************************************/
    
    public class main{
        public static void PrintMatrix(int[][] matrix, int leftRow, int leftColumn, int rightRow, int rightColumn) {
            if (leftRow == rightRow) {
                for (int i = leftColumn; i < (rightColumn + 1); i++)
                    System.out.println(matrix[leftRow][i] + " ");
            } else if (leftColumn == rightColumn) {
                for (int i = leftRow; i < (rightRow + 1); i++)
                    System.out.println(matrix[i][leftColumn] + " ");
            } else {
                int curRow = leftRow, curColumn = leftColumn;
    
                for(; curColumn != rightColumn; curColumn++)
                    System.out.println(matrix[leftRow][curColumn] + " ");
                for(; curRow != rightRow; curRow++)
                    System.out.println(matrix[curRow][rightColumn]);
                for(; curColumn != leftColumn; curColumn--)
                    System.out.println(matrix[rightRow][curColumn]);
                for(; curRow != leftRow; curRow--)
                    System.out.println(matrix[curRow][leftColumn]);
            }
        }
    
        public static void CirclePrintingMatrix(int [][] matrix){
            int leftRow = 0, leftColumn = 0;
            int rightRow = matrix.length - 1, rightColumn = matrix[0].length - 1;
    
            while(leftRow < (rightRow + 1) && leftColumn < (rightColumn + 1))
                PrintMatrix(matrix, leftRow++, leftColumn++, rightRow--, rightColumn--);
        }
    
        public static void main(String[] args){
            int [][] matrix = {
                {1,2,3,4},
                {5,6,7,8},
                {9,10,11,12},
                {13,14,15,16}
            };
            CirclePrintingMatrix(matrix);
        }
    }
    
  • 相关阅读:
    python处理url中的中文编码,以及其他编码问题
    深度学习与神经网络
    Windows下为64位的python3.4.3安装numpy
    TOP 10开源的推荐系统简介
    遗传算法
    java调用c++生成的动态和静态库时遇到的问题
    java程序(一)----HashMap同时获取键值
    Deep Learning In NLP 神经网络与词向量
    word2vec使用说明
    Spring入门_02_属性注入
  • 原文地址:https://www.cnblogs.com/AlexKing007/p/12338082.html
Copyright © 2011-2022 走看看