59. Spiral Matrix II

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

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
Tip: The same is divided into four steps, and the rows and columns are represented by i j and its deformation and exchange position.

Answer:

class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> > ret( n, vector<int>(n) );
        	int k = 1, i = 0;
        	while( k <= n * n )
        	{
        		int j = i;
                    // four steps
        		while( j < n - i )             // 1. horizonal, left to right
        			ret [i] [j ++] = k ++;
        		j = i + 1;
        		while( j < n - i )             // 2. vertical, top to bottom
        			ret [j ++] [ni-1] = k ++;
        		j = n - i - 2;
        		while( j > i )                  // 3. horizonal, right to left
        			ret [ni-1] [j--] = k ++;
        		j = n - i - 1;
        		while( j > i )                  // 4. vertical, bottom to  top
        			ret [j -] [i] = k ++;
        		i++;      // next loop
        	}
        	return ret;
        }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324763106&siteId=291194637