[力扣] 算法 59 (C#)

59. 螺旋矩阵 II

public class Solution {
    public int[][] GenerateMatrix(int n) {
        var ret = new int[n][];
        for (var i = 0; i < ret.Length; i++)
            ret[i] = new int[n];
        var loc = (x:0, y:0);
        var dir = (x:0, y:1);
        for(var i = 0; i < n * n; i++)
        {
            ret[loc.x][loc.y] = i + 1;
            var next = (x:loc.x + dir.x, y:loc.y + dir.y);
            if(next.x < 0 || next.y<0||next.x == n || next.y == n || ret[next.x][next.y] != 0)
            {
                dir = (dir.y, -dir.x);
                next = (x: loc.x + dir.x, y: loc.y + dir.y);
            }
            loc = next;
        }
        return ret;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据