Simple and easy to understand C# solution


  • 0
    J

    public class Solution {
    public int[,] GenerateMatrix(int n) {
    int[,] mt = new int[n,n];
    int end = n*n, num = 1, i = 0;
    while(num < end){
    int edge = n - 1 - i, j = i;
    while (j < edge) mt[i, j++] = num++;
    while (i < edge) mt[i++, j] = num++;
    edge = n - 1 - edge;
    while (j > edge) mt[i, j--] = num++;
    while (i > edge) mt[i--, j] = num++;
    i++;
    }
    if (n % 2 == 1) mt[i,i] = num;
    return mt;
    }
    }


  • 0
    J
    public int[,] GenerateMatrix(int n) {
        int[,] mt = new int[n,n];
        int end = n*n, num = 1, i = 0;
        while(num < end){
            int edge = n - 1 - i, j = i;
            while (j < edge) mt[i, j++] = num++;
            while (i < edge) mt[i++, j] = num++;
            edge = n - 1 - edge;
            while (j > edge) mt[i, j--] = num++;
            while (i > edge) mt[i--, j] = num++;
            i++;
        }
        if (n % 2 == 1) mt[i,i] = num;
        return mt;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.