[置顶] 生成螺旋矩阵(方阵、矩阵)

54. Spiral Matrix

My Submissions
Question Editorial Solution
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;
}


你可能感兴趣的:(算法)