zoukankan      html  css  js  c++  java
  • 剑指 Offer 29. 顺时针打印矩阵

    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            //判空
            if(matrix.length == 0){
                return new int[0];
            }
            //定义矩阵 上下左右的边界
            int left = 0;
            int right = matrix[0].length - 1;
            int top = 0;
            int bottom = matrix.length - 1;
            //定义 存放的数组 res,及数组的下标index
            int[] res = new int[(right + 1) * (bottom + 1)];
            int index = 0;
            while(true){
                //从左往右
                for(int i = left;i <= right;i++){
                    res[index++] = matrix[top][i];
                }
                if(++top > bottom){
                    break;
                }
                //从上往下
                for(int i = top;i <= bottom;i++){
                    res[index++] = matrix[i][right];
                }
                if(left > --right){
                    break;
                }
                //从右往左
                for(int i = right; i >= left;i--){
                    res[index++] = matrix[bottom][i];
                }
                if(top > --bottom){
                    break;
                }
                //从下往上
                for(int i = bottom;i >= top; i--){
                    res[index++] = matrix[i][left];
                }
                if(++left > right){
                    break;
                }
            }
            return res;
        }
    }
  • 相关阅读:
    博客园如何运行代码
    视觉差
    h5 播放器 -3
    播放器 视频 音频 -1
    游戏 保卫萝卜
    跟踪算法
    走口字

    联动日历
    jq 抽奖
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14135135.html
Copyright © 2011-2022 走看看