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 ]
]

class Solution {
public:
    /**
     * @param n an integer
     * @return a square matrix
     */
    vector<vector<int>> generateMatrix(int n) {
        // Write your code here
        vector<vector<int> > result = vector<vector<int> >(n, vector<int>(n, 0));
	    int start = 0;
	    int end = n-1;

	    int num = 1;
	    while (start < end)
	    {
		    for (int i = start; i < end; i++)
		    {
			    result[start][i] = num++;
		    }

		    for (int i = start; i < end; i++)
		    {
			    result[i][end] = num++;
		    }

		    for (int i = end; i > start; i--)
		    {
			    result[end][i] = num++;
		    }

		    for (int i = end; i > start; i--)
		    {
			    result[i][start] = num++;
		    }

		    start++;
		    end--;
	    }

    	if (start == end)
	    {
		    result[start][end] = num;
	    }
	    return result;
    }
};


你可能感兴趣的:(Spiral Matrix II)