C 0MS with explantion online


  • 0
    Y
     #define MAX 100
    int** generateMatrix(int n) {
    int direct[4][2] = {0,1,1,0,0,-1,-1,0};
    int sx=0,sy=0,visited[MAX][MAX],m=n*n,orient=0,i,x,y;
    memset(visited,0,sizeof(visited));
    int **result = (int**)malloc(sizeof(int*)*n);
    for(i=0;i<n;i++)
        result[i] = (int*)malloc(sizeof(int)*n);
    for(i=1;i<=m;i++){
        result[sx][sy] = i;
        visited[sx][sy] = 1;
        x = sx+direct[orient][0];y = sy+direct[orient][1];
        if(x>=n || x<0 || y>=n || y<0 || visited[x][y])
            orient = (orient+1)%4;
        sx = sx+direct[orient][0];
        sy = sy+direct[orient][1];      
    }
    
    return result;
    }

Log in to reply
 

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