- 輸入一個矩陣,按照從外向里以順時針的順序依次打印出每一個數(shù)字
- 例如,如果輸入如下矩陣
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
- 則依次打印出數(shù)字1、2、3、4、8、12、16、15、14、13、9、5、6、7、11、10
題目解讀
代碼
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> temp;
int row = 0;
int col = 0;
int rows = matrix.size() - 1;
int cols = matrix[0].size() -1;
while(row <= rows && col <= cols){
// 向右
if(row <= rows && col <= cols){
for(int j = col; j <= cols; j ++){
temp.push_back(matrix[row][j]);
}
row ++;
}
// 向下
if(row <= rows && col <= cols){
for(int i = row; i <= rows; i ++){
temp.push_back(matrix[i][cols]);
}
cols --;
}
// 向左
if(row <= rows && col <= cols){
for(int j = cols; j >= col; j --){
temp.push_back(matrix[rows][j]);
}
rows --;
}
// 向上
if(row <= rows && col <= cols){
for(int i = rows; i >= row; i --){
temp.push_back(matrix[i][col]);
}
col ++;
}
}
return temp;
}
void create(vector<vector<int> > &matrix){
vector<int> a;
for(int i = 1; i <= 16; i ++){
a.push_back(i);
if(i%4 == 0){
matrix.push_back(a);
a.clear();
}
}
for(int i=0; i < matrix.size(); i++){
for(int j=0; j < matrix[0].size(); j++){
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
};
main(){
vector<vector<int> > matrix;
Solution ss;
ss.create(matrix);
vector<int> tt = ss.printMatrix(matrix);
for(int i=0; i < tt.size(); i++){
cout<<tt[i]<<" ";
}
cout<<endl;
}
總結展望
- 不涉及數(shù)據(jù)結構和算法,僅僅是考驗編程基本功,本題相當?shù)轿?/li>
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。