【发布时间】:2021-09-08 22:28:37
【问题描述】:
所以我正在尝试创建一个函数以螺旋顺序填充 1 个矩阵 有点像这样
1 2 3
8 9 4
7 6 5
我正在尝试先填充外部,然后使用相同类型的递归函数来填充不小的内部,但我只有 1 个内部:
1 2 3 4
12 1 1 5
11 1 1 6
10 9 8 7
这里是我使用的代码
#include <iostream>
#include <vector>
using namespace std;
void spiral_making(int sr,int sc,int er,int ec,int counter,vector< vector<int>>*so1){
//sr :starting row
//sc : stating column
//er : ending row
//ec : ending column
int i; //iterator
//insert the first row into the matrix
if((sr-er==1)||(sc-ec==1)){(*so1)[sr][sc]= counter;}
{
for(i=sc;i<ec;i++){
(*so1)[sr][i]=counter;
counter++;
}
//increse the starting row by 1
sr++;
//insert the back
for (i=sr;i<er;i++){
(*so1)[i][ec-1]=counter;
counter++;
}
//then I reduced the ending column by 1
//insert the bottom row (but it will be back ward)
ec--;
for(i=ec;i>sc;i--){
(*so1)[er-1][i-1]=counter;
counter++;
}
//then i insert the left size column(but it also go backward)
for(i=er-1;i>sr;i--){
(*so1)[i-1][sc]=counter;
counter++;
}
//then I icrease starting column and decrease ending row
er--;
sc++;
//check if there are any small matrix inside if yes then conduct this function again with the smaller matrix
if((er<sr)&&(sc<ec)){
spiral_making(sr,sc,er,ec,counter,&(*so1));
}
}
}
int main(){
//input section
int n;
do{
std::cout<<"please input the number greater than 1: ";
cin>>n;
}
while(n<0);
//try to work out with the matrix
vector< vector<int> > so(n,vector<int>(n,1));
spiral_making(0,0,n,n,1,&so);
//print the output
for (int u=0;u<n;u++){
for(int y=0;y<n;y++){
std::cout<<so[u][y]<<" ";
}
std::cout<<std::endl;
}
return 0;
}
我有点新,所以请原谅我这个愚蠢的问题:)))
【问题讨论】:
-
&(*so1)可以简单地为so1。 -
条件
er<sr在第一次调用时可能为假,因此永远不会进行递归调用。你的意思是相反的比较吗?