[LeetCode]59. Spiral Matrix II

59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]


題意:

給定一個整數n,生成一個包含1到n*n所有元素的螺旋形矩陣。


1,二維數組的動態空間分配(int **array大小爲m*n):
  1)首先分配m個的指針單元:
   int **array = (int **)malloc( sizeof(int *) * m );
  2)接着分配n個字符的單元:
   for ( cnt = 0; cnt < n; cnt += 1 )
   {
       array[cnt] = (int *)malloc( sizeof( int ) * n );
   }

注意:
    分配指針單元時sizeof的參數是指針。
    
2,二維數組動態內存的釋放:
   for ( cnt = 0; cnt < n; cnt += 1 )
   {
       free( (void *)array[cnt] );
   }

  free( (void *)array );
  
3,變量含義:
定義brow代表從左到右執行的次數,erow代表從右到左執行的次數;bcol代表從下往上讀取次數,ecol代表從上往下讀取次數。所以有:
1)從左往右讀取時,必須從bcol列開始讀取,遞增直到ecol列。
2)從右往左讀取時,必須從ecol列開始讀取,遞減直到bcol列。
2)從上往下讀取時,必須從brow行開始讀取,遞增直到erow行。
4)從下往上讀取時,必須從erow行開始讀取,遞減直到brow行。

其他規則同《[LeetCode]54. Spiral Matrix


/**
 * Return an array of arrays.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int** generateMatrix(int n) 
{
    if ( n <= 0 )
    {
        return NULL;
    }
    
    int **array = (int **)malloc( sizeof( int *) * n  );
    if ( !array )
    {
        return NULL;
    }
    
    int cnt = 0;
    for ( cnt = 0; cnt < n; cnt += 1 )
    {
        array[cnt] = (int *)malloc( sizeof( int ) * n );
    }
    
    int brow = 0;
    int erow = n - 1;
    int bcol = 0;
    int ecol = n - 1;
    int times = 1;                                                                               
    int value = 1;
    cnt = 0;
    while ( cnt < n * n ) 
    {   
        if ( times % 4 == 1 )
        {
            int count = bcol;
            while ( count <= ecol )
            {
                array[brow][count] = value;
                count += 1;
                value += 1;
            }
            
            cnt = cnt + count - bcol;
            brow += 1;
        }
        else if ( times % 4 == 2 )
        {
            int count = brow;
            while ( count <= erow )
            {
                array[count][ecol] = value;
                count += 1;
                value += 1;
            }
            
            cnt = cnt + count - brow;
            ecol -= 1;
        }
        else if ( times % 4 == 3 )
        {
            int count = ecol;
            while ( count >= bcol )
            {
                array[erow][count] = value;
                count -= 1;
                value += 1;
            }
            
            cnt = cnt + ecol - count;
            erow -= 1;
        }
        else
        {
            int count = erow;
            while ( count >= brow )
            {
                array[count][bcol] = value;
                count -= 1;
                value += 1;
            }
            
            cnt = cnt + erow - count;
            bcol += 1;
        }
        times += 1;
    }
    
    return array;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章