Leetcode之Spiral MatrixII

題目:

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

代碼:

方法一(使用bool數組):

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        	vector<vector<int> > res;
	if (n <= 0)return res;
	if (n == 1) {
		vector<int> v = { 1 };
		res.push_back(v);
		return res;
	}
	res = vector<vector<int>>(n, vector<int>(n, 0));
	vector<vector<bool> > v(n, vector<bool>(n, false));
	int value = 1;

	for (int i = 0, j = 0; !v[i][j];) {
		while (j < n && !v[i][j]) {
			res[i][j] = value;
			v[i][j] = true;
			value++;
			j++;
		}
		j--; i++;
		while (i < n && !v[i][j]) {
			res[i][j] = value;
			v[i][j] = true;
			value++;
			i++;
		}
		i--; j--;
		while (j >= 0 && !v[i][j]) {
			res[i][j] = value;
			v[i][j] = true;
			value++; j--;
		}
		j++; i--;
		while (i >= 0 && !v[i][j]) {
			res[i][j] = value;
			v[i][j] = true;
			value++; i--;
		}
		i++; j++;
	}

	return res;
    }
};

方法二(不使用布爾數組):

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        		vector<vector<int> > res;
	if (n <= 0)return res;
	if (n == 1) {
		vector<int> v = { 1 };
		res.push_back(v);
		return res;
	}
	res = vector<vector<int>>(n, vector<int>(n, 0));
	
	int value = 1;
	
	for (int i = 0, j = 0;res[i][j]==0;) {
		while (j < n && res[i][j] == 0) {
			res[i][j] = value;		
			value++;
			j++;
		}
		j--; i++;
		while (i < n && res[i][j] == 0) {
			res[i][j] = value;
			
			value++;
			i++;
		}
		i--; j--;
		while (j >= 0 && res[i][j] == 0) {
			res[i][j] = value;
			
			value++; j--;
		}
		j++; i--;
		while (i >= 0 && res[i][j] == 0) {
			res[i][j] = value;
			value++; i--;
		}
		i++; j++;
	}

	return res;
    }
};

想法:有時候解一道題的時候可以想想有沒有什麼別的解法

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