zoukankan      html  css  js  c++  java
  • 剑指offer_19:顺时针打印矩阵

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

    示例 1:
    输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    输出:[1,2,3,6,9,8,7,4,5]

    示例 2:
    输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    输出:[1,2,3,4,8,12,11,10,9,5,6,7]

    限制:
    0 <= matrix.length <= 100
    0 <= matrix[i].length <= 100

    1、模拟运算

    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if(matrix.length==0) return new int[0];
            int row=matrix.length;
            int col=matrix[0].length;
            int num=row*col;
            int[] res=new int[num];
            boolean[][] flag=new boolean[row][col];
            int[][] gowhere={{0,1},{1,0},{0,-1},{-1,0}};
            int i=0,j=0;
            int index=0;
            for(int k=0;k<num;k++){
                res[k]=matrix[i][j];
                flag[i][j]=true;
                int newi=i+gowhere[index][0],newj=j+gowhere[index][1];
                if(newj>=col||newi>=row||newj<0||newi<0||flag[newi][newj]==true){
                    index++;
                    index%=4;
                }
                i+=gowhere[index][0];
                j+=gowhere[index][1];
            }
            return res;
        }
    }
    

    2、边界

    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if(matrix.length==0) return new int[0];
            int row=matrix.length;
            int col=matrix[0].length;
            int[] res=new int[row*col];
            int left=0,top=0,right=col-1,bottom=row-1;
            int index=0;
            while(left<=right&&top<=bottom){
                for(int j=left;j<=right;j++){
                    res[index++]=matrix[top][j];
                }
                for(int i=top+1;i<=bottom;i++){
                    res[index++]=matrix[i][right];
                }
                if(top<bottom){
                    for(int j=right-1;j>=left;j--){
                        res[index++]=matrix[bottom][j];
                    }
                }
                if(left<right){
                    for(int i=bottom-1;i>top;i--){
                        res[index++]=matrix[i][left];
                    }
                }
                left++;
                right--;
                top++;
                bottom--;
            }
            return res;
        }
    }
    
  • 相关阅读:
    量化投资_期货日内交易几个问题的考证
    量化投资_上一个交易时间段对今日收盘价涨跌的影响
    RunJS
    sublime3快捷 输入html
    NLP学习资源
    Invert Binary Tree
    定时任务 Crontab命令 详解
    根据职位名,自动生成jd
    使用python + tornado 做项目demo演示模板
    Awk 实例
  • 原文地址:https://www.cnblogs.com/xyz-1024/p/14149389.html
Copyright © 2011-2022 走看看