Spiral matrix (C++ solution)

topic

Given a   matrix of m rows and columns   , please   return all elements in the matrix in clockwise spiral order .nmatrix

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
 Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 Output: [1,2,3,4,8,12, 11,10,9,5,6,7]

C++ code

#include <iostream>
#include <vector>
using namespace std;

/*
* 首先设定上下左右边界(left,right,top,bottom)
* 其次向右移动到最右,此时第一行因为已经使用过了,可以将其从图中删去,体现在代码中就是重新定义上边界
* 判断若重新定义后,上下边界交错,表明螺旋矩阵遍历结束,跳出循环,返回答案
*/
vector<int> spiralOrder(vector<vector<int>>& matrix) {
	vector<int> ans;
	if (matrix.empty()) {
		return ans;
	}
	int left = 0, right = matrix[0].size() - 1, top = 0, bottom = matrix.size() - 1;
	while (true) {
		for (int i = left; i <= right; ++i) ans.push_back(matrix[top][i]);
		if (++top > bottom) break;
		for (int i = top; i <= bottom; ++i) ans.push_back(matrix[i][right]);
		if (--right < left) break;
		for (int i = right; i >= left; --i) ans.push_back(matrix[bottom][i]);
		if (--bottom < top) break;
		for (int i = bottom; i >= top; --i) ans.push_back(matrix[i][left]);
		if (++left > right) break;
	}
	return ans;
}
int main() {
	vector<vector<int>> matrix = { {1,2,3},{4,5,6},{7,8,9} };
	vector<int> ans = spiralOrder(matrix);
	for (int i = 0; i < ans.size(); i++) {
		cout << ans[i] << " ";
	}
	cout << endl;
	return 0;
}

analyze

First set the upper, lower, left and right boundaries (left, right, top, bottom), and then move to the right. At this time, because the first line has already been used, it can be deleted from the picture. This is reflected in the code by re- Define the upper boundary. If the judgment is redefined, the upper and lower boundaries are interlaced, indicating that the spiral matrix traversal is completed, the loop is jumped out, and the answer is returned.

Guess you like

Origin blog.csdn.net/m0_62275194/article/details/133860335