c++编程回形取数问题
发布网友
发布时间:2023-05-02 10:08
我来回答
共2个回答
热心网友
时间:2023-11-06 15:20
#include <cstdio>
const int MAXM = 200 + 10;
int m, n;
int num[MAXM][MAXM] = {0};
int ans[MAXM*MAXM];
int tempo = 0;
void init()
{
scanf("%d %d",&m,&n);
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d",&num[i][j]);
}
}
}
void solve(int beginrow, int beginline, int row, int line)
{
int i, j;
if (row == 0 || line == 0) return;
if (row == 1)
{
for (i = 0; i < line; i++)
{
ans[tempo] = num[beginrow][beginline];
beginline++;
tempo++;
}
return;
}
if (line == 1)
{
for (i = 0; i < row; i++)
{
ans[tempo] = num[beginrow][beginline];
beginrow++;
tempo++;
}
return;
}
int v = beginrow, h = beginline;
ans[tempo] = num[beginrow][beginline];
tempo++;
for (i = 0; i < row-1; i++)
{
v++;
ans[tempo] = num[v][h];
tempo++;
}
for (i = 0; i < line-1; i++)
{
h++;
ans[tempo] = num[v][h];
tempo++;
}
for (i = 0; i < row-1; i++)
{
v--;
ans[tempo] = num[v][h];
tempo++;
}
for (i = 0; i < line-2; i++)
{
h--;
ans[tempo] = num[v][h];
tempo++;
}
solve(v+1,h,row-2,line-2);
}
void output()
{
int cnt = n*m;
if (cnt == 0) return;
printf("%d",ans[0]);
for (int i = 1; i < cnt; i++)
{
printf(" %d",ans[i]);
}
printf("\n");
}
int main()
{
init();
int begin1 = m, begin2 = n;
solve(0,0,begin1, begin2);
output();
return 0;
}
请参考,欢迎交流哈。
热心网友
时间:2023-11-06 15:21
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[250][250];
int main(){
int n, m;
// memset(vis, 0, sizeof(vis));
memset(a, -1, sizeof(a));
cin >> n >> m;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
scanf("%d", &a[i][j]);
}
}
int x = -1, y = 0, cnt = 0;
while(cnt < n * m){
while(x + 1 < n && a[x + 1][y] != -1){
printf("%d ", a[++x][y]);
a[x][y] = -1;
cnt++;
}
while(y + 1 < m && a[x][y + 1] != -1){
printf("%d ", a[x][++y]);
a[x][y] = -1;
cnt++;
}
while(x - 1 >= 0 && a[x - 1][y] != -1){
printf("%d ", a[--x][y]);
a[x][y] = -1;
cnt++;
}
while(y - 1 >= 0 && a[x][y - 1] != -1){
printf("%d ", a[x][--y]);
a[x][y] = -1;
cnt++;
}
}
cout << endl;
return 0;
}
代码转载于:网页链接
题目的资源:网页链接