题解 | #螺旋矩阵#

螺旋矩阵

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

import java.util.ArrayList;

public class Solution {

    public ArrayList<IntegerspiralOrder(int[][] matrix) {

        ArrayList<Integerres = new ArrayList<Integer>();

        if(matrix.length==0) {

            return res;

        }

        int i = 0, j = 0;

        int[][] a = new int[matrix.length][matrix[0].length];

        int count = 1;

        int[][] direction = {

            {01},

            {10},

            {0, -1},

            {-10}

        };

        int directionNumber = 0;

        res.add(matrix[0][0]);

        a[0][0] = 1;

        while (count < (matrix.length * matrix[0].length)) {

            i += direction[directionNumber % 4][0];

            j += direction[directionNumber % 4][1];

            if (i >= 0 && j >= 0 && i < matrix.length && j < matrix[0].length &&

                    a[i][j] != 1) {

                res.add(matrix[i][j]);

                a[i][j] = 1;

                count++;

            } else {

                i -= direction[directionNumber % 4][0];

                j -= direction[directionNumber % 4][1];

                directionNumber++;

            }

        };

        return res;

    }

}

全部评论

相关推荐

wuwuwuoow:Redisson 写错了,记得 Redis 儿子以后都不会写错。其他没啥问题,海投就行。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务