C++刷leetcode(面试题29. 顺时针打印矩阵)【边界】
本帖最后由 糖逗 于 2020-5-8 18:07 编辑题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [,,]
输出:
示例 2:
输入:matrix = [,,]
输出:
限制:
0 <= matrix.length <= 100
0 <= matrix.length <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#include <vector>
#include <iostream>
using namespace std;
vector<int> solution(vector<vector<int> >& matrix){
vector<int> res;
if(matrix.size() == 0 || matrix.size() == 0) return res;
int top = 0;
int bottom = matrix.size() - 1;
int left = 0;
int right = matrix.size() - 1;
while(true){
for(int i = left; i <= right; i++){
res.push_back(matrix);
}
top++;
if(top > bottom) break;
for(int i = top; i <= bottom; i++){
res.push_back(matrix);
}
right--;
if(right < left) break;
for(int i = right; i >= left; i--){
res.push_back(matrix);
}
bottom--;
if(bottom < top) break;
for(int i = bottom; i >= top; i--){
res.push_back(matrix);
}
left++;
if(left > right) break;
}
return res;
}
int main(void){
int row;
vector<vector<int> > input;
cout << "please send row" << endl;
cin >> row;
input.resize(row);
int columns;
cout << "please send columns" << endl;
cin >> columns;
int number;
for(int i = 0; i < row; i++){
for(int j = 0; j < columns; j++){
cin >> number;
input.push_back(number);
}
}
vector<int> res = solution(input);
for(int i = 0; i < res.size(); i++){
cout <<res;
}
cout << endl;
return 0;
}
注意事项:
1.考察边界问题。
{:10_308:}
页:
[1]