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


class Solution {
public:
	vector<vector<int>> generateMatrix(int n) {
		vector<vector<int>>matrix(n);
		if(n==0)
		    return matrix;
		for (int i = 0; i < n; i++)
			matrix[i].resize(n);
		if (n == 1)
		{
			matrix[0][0] = 1;
			return matrix;
		}
		int k = 1;
		int off = 0;
		while (true)
		{
			for (int i = off; i < matrix[0].size() - off; i++)
			{
				matrix[off][i] =k++;
			}
			if (k == n*n + 1)
				return matrix;
			for (int i = off + 1; i < matrix.size() - off; i++)
			{
				matrix[i][matrix.size() - 1 - off] = k++;
			}
			for (int i = matrix.size() - 2 - off; i >= off; i--)
			{
				matrix[matrix.size() - 1 - off][i] = k++;
			}
			for (int i = matrix.size() - 2 - off; i >= off + 1; i--)
			{
				matrix[i][off] =  k++;
			}
			if (k == n*n + 1)
				return matrix;
			off++;
		}
	}
};

accepted

你可能感兴趣的:(LeetCode)