gpt4 book ai didi

c - 寻找方阵中的中心

转载 作者:行者123 更新时间:2023-11-30 15:01:56 25 4
gpt4 key购买 nike

我的问题是关于方阵的。我有一个动态数组,以便填充从 1 到 N 的数字,从“中心”开始并螺旋向外。如果我有一个6x6的数组,我需要按照图中所示的方式填充它。如果我有一个在每个方向上都有偶数个单元格的数组,我需要在数组中挑选一个正方形,并开始从正方形中的第一个元素开始计数。但是如果我有一个包含奇数个单元格的数组,我需要选出数组的中心。

enter image description here

我的主要问题是想出一种算法可以帮助我到达我的“中心”。这是我用于创建和打印数组的代码:

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

int** create_array(int, int);
void fill(int **, int, int);
void print_my_array(int**, int, int);
void print_my_array(int** , int , int );
int main() {

int **a, x, y;
printf("Enter x: ");
scanf("%d", &x);
printf("Enter y: ");
scanf("%d", &y);

a = create_array(x, y);
fill(a, x, y);
print_my_array(a, x, y);
return 0;
}

int** create_array(int rows, int cols) {
int **arr=NULL,i;
if (!(arr = (int**)malloc(rows*sizeof(int*)))) {
printf("Error");
exit(0);
}
for ( i = 0; i <rows; i++){
if (!(arr[i] = (int*)malloc(cols*sizeof(int)))) {
printf("Error");
exit(0);
}
return arr;
}
return arr;
}

void fill(int **arr, int x, int y) {
//HELP
}

void print_my_array (int** array, int x, int y)
{
int i, j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
printf("\n");
}

最佳答案

nxn 数组的中心是 (floor((n-1)/2),floor((n-1)/2)) [0 索引]。但我们会以不同的方式解决它。如果 n 是偶数,则结束于

x x x 16
x 1 x x
x x x x
x x x x

x x x x x 36
x x x x x x
x x 1 x x x
x x x x x x
x x x x x x
x x x x x x

因此,即使是 n,它也始终以 [0,n-1] 结尾。现在你会做什么来填补它?

您知道数字将为n*n, n*n-1,n*n-2...2,1

类似地,对于 n 个奇数

x x x
x 1 x
9 x x

x x x x x
x x x x x
x x 1 x x
x x x x x
25 x x x x

希望您从这些图片中得到我们想要做的事情?

代码

int nc=n*n;
int ans[n][n];
fill ans[][] with -1
int row=n-1,col=0;
if(n&1)
{
while(nc>0)
{
for(int i=row;i>=0 && ans[i][col]==-1;i--)
{
row--;ans[i][col]=nc; nc--;
}
row++;col++;
for(int j=col;j<=n-1 && ans[row][j]==-1;j++)
{
col++;ans[row][j]=nc; nc--;
}
col--;row++;
for(int i=row;i<=n-1 && ans[i][col]==-1;i++)
{
row++;ans[i][col]=nc;nc--;
}
row--;col--;
for(int j=col;j>=0 && ans[row][j]==-1;j--)
{
col--;ans[row][j]=nc;nc--;
}
col++;row--;
}

}
else

{
row=0;col=n-1;
while(nc>0)
{

for(int i=row;i<=n-1 && ans[i][col]==-1;i++)
{
row++;ans[i][col]=nc;nc--;
}
row--;col--;
for(int j=col;j>=0 && ans[row][j]==-1;j--)
{
col--;ans[row][j]=nc;nc--;
}
col++;row--;
for(int i=row;i>=0 && ans[i][col]==-1;i--)
{
row--;ans[i][col]=nc; nc--;
}
row++;col++;db(row);db(col);

for(int j=col;j<=n-1 && ans[row][j]==-1;j++)
{
col++;ans[row][j]=nc; nc--;
}
col--;row++;
}
}
//print ans[n][n]

关于c - 寻找方阵中的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com