plduhoux
2/22/2018 - 6:42 PM

spiralNumbers

int[][] spiralNumbers(int n) {
    int[][] res = new int[n][n];
    int x = 0, y = 0, d = 0;
    for (int i = 0; i < n * n; i++) {
        res[x][y] = i + 1;
        if (d == 1) {
            x++;
            if (x == n || res[x][y] != 0) {
                x--;
                y--;
                d = 2;
            }
        } else if (d == 0) {
            y++;
            if (y == n || res[x][y] != 0) {
                y--;
                x++;
                d = 1;
            }
        } else if (d == 3) {
            x--;
            if (x < 0 || res[x][y] != 0) {
                x++;
                y++;
                d = 0;
            }
        } else if (d == 2) {
            y--;
            if (y < 0 || res[x][y] != 0) {
                y++;
                x--;
                d = 3;
            }
        }
    }
    return res;
}