顺时针打印矩阵

题目

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

示例

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

思考

  • 设置上下左右边界,用for循环一圈一圈的进行顺时针输出

代码

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0)
            return new int[0];
        int c = matrix[0].length, r = matrix.length;
        int[] array = new int[c * r];
        int count = 0, top = 0, bottom = r - 1,
                left = 0, right = c - 1;
        while (count != array.length) {
            for (int i = left; i <= right; i++) {
                if (count == array.length)
                    return array;
                array[count++] = matrix[top][i];
            }
            for (int i = top + 1; i <= bottom; i++) {
                if (count == array.length)
                    return array;
                array[count++] = matrix[i][right];
            }
            for (int i = right - 1; i > left; i--) {
                if (count == array.length)
                    return array;
                array[count++] = matrix[bottom][i];
            }
            for (int i = bottom; i > top; i--) {
                if (count == array.length)
                    return array;
                array[count++] = matrix[i][left];
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return array;
    }
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇