问题描述:
有一个二维数组,将它每个元素按照螺旋方式排序
比如原始数组如下
排序后的结果为:
代码
#include "stdlib.h"
#include "stdio.h"
//#define M 21
//#define N 17
void print(int ** arr, int x_size, int y_size)
{
int i = 0, j = 0;
for(i = 0; i < x_size; i++){
for(j = 0; j < y_size; j++){
printf("%03d ", arr[i][j]);
}
printf("\n");
}
}
void ** alloc_arr(int x_size, int y_size)
{
int ** ret;
ret = (int**)malloc(x_size * sizeof(int*));
int i = 0;
for(i = 0; i < x_size; i++){
ret[i] = (int*)malloc(y_size * sizeof(int));
}
return ret;
}
void free_arr(void ** arr, int x_size, int y_size)
{
int i = 0;
for(i = 0; i < x_size; i++){
free(arr[i]);
}
free(arr);
}
void turns_arr(int ** arr1, int pos, int m, int n, int **arr2, int top, int bottom, int left, int right)
{
int index = 0;
if(top==bottom&&left==right){
int x1 = pos/n;
int y1 = pos-x1*n;
arr2[top][left] = arr1[x1][y1];
return;
}
//printf("top=%d,bottom=%d,left=%d,right=%d\n", top,bottom,left,right);
for(index = 0; index+pos < m*n; index++){
int x1 = (pos+index)/n;
int y1 = (pos+index-x1*n);
//printf("x1=%d,y1=%d\n",x1,y1);
int x2,y2;
int x_size = bottom-top;
int y_size = right-left;
if(index < y_size){
//printf("top\n");
x2 = top;
y2 = left+index;
}else if(index < x_size+y_size){
//printf("right\n");
x2 = index-y_size+top;
y2 = right;
}else if(index < 2*y_size+x_size){
//printf("bottom\n");
x2 = bottom;
y2 = right-(index-x_size-y_size);
}else if(index < 2*x_size+2*y_size){
//printf("left\n");
x2 = bottom-(index-2*y_size-x_size);
y2 = left;
}else{
if(bottom-top==1 || right-left==1){
return;
}
top+=1,bottom-=1,left+=1,right-=1;
turns_arr(arr1, pos+index, m, n, arr2, top, bottom, left, right);
break;
}
//printf("x2=%d,y2=%d\n", x2, y2);
arr2[x2][y2] = arr1[x1][y1];
}
}
void main(int argc, char ** argv)
{
int **a, **b;
if(argc < 3){
return;
}
int M = atoi(argv[1]);
int N = atoi(argv[2]);
if(M == 0 || N == 0){
return;
}
a = alloc_arr(M, N);
b = alloc_arr(M, N);
int i = 0, j = 0;
int k = 1;
for(i = 0; i < M; i++){
for(j = 0; j < N; j++){
a[i][j] = k++;
}
}
print(a, M, N);
//printf("=========================================================\n");
for(i = 0; i < N*4-1; i++)
printf("=");
printf("\n");
turns_arr(a, 0, M, N, b, 0, M-1, 0, N-1);
print(b, M, N);
//释放a,b
free_arr(a, M, N);
free_arr(b, M, N);
}
演示结果:
gcc -o AAA main.c