1. 程式人生 > >59.螺旋矩陣II

59.螺旋矩陣II

59.螺旋矩陣II
附加除錯

class Solution {
public:
	vector<vector<int>> generateMatrix(int n) {
		vector<vector<int>>matrix(n, vector<int>(n));
		dis(matrix);
		int x = 0, y = 0;
		bool x_axis = 0, y_axis = 0;
		for (int i = 1; i < pow(n, 2) + 1; ++i) {
			if (!x_axis &&
!y_axis) { matrix[x][y] = i; y++; if (y == n || matrix[x][y] != 0) x++, y--, y_axis = 1; } else if (!x_axis&&y_axis) { matrix[x][y] = i; x++; if (x == n || matrix[x][y] != 0) y--, x--, x_axis = 1; } else if (x_axis&&y_axis) { matrix[
x][y] = i; y--; if (y < 0||matrix[x][y] != 0) x--, y++, y_axis = 0; } else if (x_axis && !y_axis) { matrix[x][y] = i; x--; if (x<0||matrix[x][y] != 0) y++, x++, x_axis = 0; } dis(matrix); } return matrix; } void dis(vector<vector<int
>>s) { system("cls"); for (int i = 0; i < s.size(); ++i) { for (int j = 0; j < s[i].size(); ++j) { cout << s[i][j] << " "; } cout << endl; } } };