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

分析:
    題意:給定一個正整型數n,返回一個n x n的矩陣,其中按照螺旋順序填充着1→n²。
    思路:這道題和LeetCode 54很相似,是一道幾何數學題,我們創建一個二維數組ans[n][n]保存結果,假設當前填充數字爲cnt,初始化爲1,且從ans[0][0]開始填寫。按照題目規則進行操作即可:向右、向下、向左、向上,每填寫完一個數字,cnt加一,直到cnt等於n²爲止。
    時間複雜度爲O(n x n )。

代碼:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        // Exceptional Case: 
		if(n == 0){
			return vector<vector<int>>();
		}
		vector<vector<int>> ans(n, vector<int>(n, 0));
		int i = 0, j = 0, cnt = 1;
		// first element
		ans[i][j] = cnt++;
		while(true){
			if(cnt > n * n){
				break;
			}
			// right
			while(j + 1 <= n - 1 && !ans[i][j + 1]){
				ans[i][j + 1] = cnt++;
				j++;
			}
			// down
			while(i + 1 <= n - 1 && !ans[i + 1][j]){
				ans[i + 1][j] = cnt++;
				i++;
			}
			// left
			while(j - 1 >= 0 && !ans[i][j - 1]){
				ans[i][j - 1] = cnt++;
				j--;
			}
			// up
			while(i - 1 >= 0 && !ans[i - 1][j]){
				ans[i - 1][j] = cnt++;
				i--;
			}
		}
		return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章