c++ - 我对带有指针输入的递归函数有疑问
问题描述
所以我正在尝试制作一个函数来以螺旋顺序填充 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;
}
我有点新,所以请原谅我这个愚蠢的问题:)))
解决方案
这是一种std::array
替代方法。也许您可以根据需要对其进行调整。
template <size_t N>
using squareArr = std::array<std::array<int, N>, N>;
template <size_t N>
void spiral(squareArr<N>& mat) {
if (mat.empty()) return;
// Counter
size_t cnt{0};
// Limits of the current circle
size_t top{0}, left{0}, right{mat[0].size()-1}, bottom{mat.size()-1};
while (top < bottom && left < right) {
// Assign clockwise in the outer circle
for (auto i=left, j=top; i<=right; i++) mat.at(j).at(i) = cnt++;
for (auto i=right, j=top+1; j<=bottom; j++) mat.at(j).at(i) = cnt++;
for (auto i=right-1, j=bottom; i>left; i--) mat.at(j).at(i) = cnt++;
for (auto i=left, j=bottom; j> top; j--) mat.at(j).at(i) = cnt++;
// Get a smaller circle
top++, left++, right--, bottom--;
}
// Center (if N is odd)
if (top == bottom && left == right) {
mat[left][top] = cnt++;
}
}
推荐阅读
- android-studio - android.process.acore 已停止并且 :app:installdebug FAILED
- applicative - F* 中的应用函子:类型检查错误
- php - 将类别列表转换为多维数组
- node.js - 本地主机上的 Botbuilder bot 没有响应,但在 Azure 中有效
- swift - 有没有办法只弃用变量的设置器?
- user-interface - 访问连续表格操作记录顺序
- ruby-on-rails - 在 Rails 中发送电子邮件的按钮
- string - 如何在不显式转换的情况下将输入读取为整数?
- javascript - 连续比较时间戳
- forms - Angular 6 patchValue 未设置..有时