生成螺旋矩陣(方陣、矩陣)

藍旭晨楓發表於2016-04-07

54. Spiral Matrix

My Submissions
Total Accepted: 56094 Total Submissions: 250811 Difficulty: Medium

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Subscribe to see which companies asked this question




方法:

(1)從外環開始,每次生成矩陣的一個環資料

(2)然後更新環的起點和大小(行數和列數)

vector<vector<int>> generateMatrix(int m, int n) {
	vector<vector<int>> res(m, vector<int>(n));

	int num_row = m, row_start = 0;
	int num_col = n, col_start = 0;
	int k = 1;

	while (num_row > 0 && num_col > 0) {
		//上邊
		for (int i = 0; i < num_col; ++i)
			res[row_start][col_start + i] = k++;

		//右邊
		for (int i = 1; i < num_row; ++i)
			res[row_start + i][col_start + num_col - 1] = k++;

		//下邊,因為第一個 for 已經至少遍歷了上邊一行,若 num_row > 1 才可能執行本 for 迴圈
		for (int i = num_col - 2; i >= 0 && num_row > 1; --i)
			res[row_start + num_row - 1][col_start + i] = k++;

		//左邊,因為第二個 for 已經至少遍歷了右邊一列,若 num_col > 1 才可能執行本 for 迴圈
		for (int i = num_row - 2; i >= 1 && num_col > 1; --i)
			res[row_start + i][col_start] = k++;

		//縮小一個單位的外環
		num_row -= 2;
		num_col -= 2;
		++row_start;
		++col_start;
	}

	return res;
}


相關文章