Spiral Matrix & Spiral Matrix II_LeetCode
Spiral Matrix II:
Description:
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的螺旋矩阵分成多层,依次按照→↓←↑的顺序来进行数字的累加。
将N/2可以得到需要进行的层数,也就是最外层循环所需的次数。
分别将行和列的起点和终点初始化,作为→↓←↑内层循环的条件。
但是要注意的是,起点和终点都是动态变化的,需要仔细思考。
如果N是奇数,最中间的数再单独赋值。
(spiral matrix的核心代码也是这样,只不过把具体的赋值改成存入一个新的vector中)
代码:
class Solution { public: vector<vector<int>> generateMatrix(int N) { vector<vector<int>> matrix(N,vector<int>(N)); int levelnum = N/2; int num = 1; int row_begin = 0; int col_begin = 0; int row_end = N-1; int col_end = N-1; for (int i = 0; i < levelnum; i++) { for (int j = col_begin; j <= col_end; j++) {//left to right matrix[row_begin][j] = num; num++; } row_begin++; for (int j = row_begin; j <= row_end; j++) {//top to bottom matrix[j][col_end] = num; num++; } col_end--; for (int j = col_end; j >= col_begin; j--) {//right to left if (row_begin<=row_end) { matrix[row_end][j] = num; num++; } } row_end--; for (int j = row_end; j >= row_begin; j--) {//bottom to top if (col_begin<=col_end) { matrix[j][col_begin] = num; num++; } } col_begin++; } if (N%2 == 1) { matrix[levelnum][levelnum] = num; } return matrix; } };
Spiral Matrix:
Description:
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]
.
解题思路:
其实和上一题没有太大的区别。
但是因为大小不再是N*N的矩阵,而是m*n的大小,因此上一题的外层循环条件level可能不适用了,改成了while循环。
代码:
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if (matrix.size() == 0) return {}; int m = matrix.size(); int n = matrix[0].size(); vector<int> result; int row_begin = 0; int col_begin = 0; int row_end = m-1; int col_end = n-1; while (row_begin <= row_end && col_begin <= col_end) { for (int j = col_begin; j <= col_end; j++) {//left to right result.push_back(matrix[row_begin][j]); } row_begin++; for (int j = row_begin; j <= row_end; j++) {//top to bottom result.push_back(matrix[j][col_end]); } col_end--; for (int j = col_end; j >= col_begin; j--) {//right to left if (row_begin<=row_end) { result.push_back(matrix[row_end][j]); } } row_end--; for (int j = row_end; j >= row_begin; j--) {//bottom to top if (col_begin<=col_end) { result.push_back(matrix[j][col_begin]); } } col_begin++; } return result; } };
-