栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

力扣剑指Offer29顺时针打印矩阵

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣剑指Offer29顺时针打印矩阵

剑指Offer29顺时针打印矩阵 思路:

模拟顺时针画矩阵的过程:

  • 填充上行从左到右
  • 填充右列从上到下
  • 填充下行从右到左
  • 填充左列从下到上

画每四条边,每画一条边都要坚持一致的左闭右开

考虑到矩阵为正方形和长方形的两种情况,所以每次放入一个元素就减一。

本题还需要注意matrix数组没有元素的情况,此时直接返回空数组即可

代码实现
class Solution {
    public int[] spiralOrder(int[][] matrix) {
        int rows = matrix.length;
        if (matrix.length == 0) {
            return new int[]{};
        }
        int columns = matrix[0].length;
        int n = rows * columns;
        int[] res = new int[n];
        
        int left = 0;
        int right = columns - 1;
        int top = 0;
        int bottom = rows - 1;
        int index = 0;
        while (top <= bottom) {
            for (int i = 0; i < right - left && n > 0; i++) {
                res[index++] = matrix[top][left + i];
                n--;
            }
            for (int i = 0; i < bottom - top && n > 0; i++) {
                res[index++] = matrix[top + i][right];
                n--;
            }
            for (int i = 0; i < right - left && n > 0; i++) {
                res[index++] = matrix[bottom][right - i];
                n--;
            }
            for (int i = 0; i < bottom - top && n > 0; i++) {
                res[index++] = matrix[bottom - i][left];
                n--;
            }
            if (left == right && top == bottom) {
                res[index++] = matrix[left][left];
            }
            top++;
            left++;
            bottom--;
            right--;
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/966193.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号