Original question
The natural number is filled into the array in a snake-like arrangement. Replace natural numbers 1, 2, 3... And N * n Insert the proper positions in the square matrix sequentially. This process is performed along the oblique column. Numbers of oblique columns: 0, 1, 2... , 2n (marked with I, n = N-1), the following data arrangement, which is a snake-like arrangement.
1 3 4 10
2 5 9 11
6 8 12 15
7 13 14 16
My ideas
Observe the following coordinates:
(0, 0) and 0
() And 1
() And 2
() And 3
() And 4 -->)
() And 5 -->)
() And 6 -->)
It is not difficult to find that as long as the number is on the same oblique line, the sum of the subscript corresponding to the array row and column is always equal.
Note: When the sum is 4 or greater than 4, you need to pay attention to the out-of-boundary issue when filling the number, so I specifically wrote a macro in the program to judge.
Implementation Code
/************************************************************************* > File Name: testmain.c > Author: KrisChou > Mail:[email protected] > Created Time: Sun 17 Aug 2014 09:04:42 PM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#define N 4#define IS_LEGAL(row,col) ((row) >= 0 && (row) < N && (col) >= 0 && (col) < N )void print(int (*arr)[N]);void fill(int (*arr)[N]);int main(int argc, char *argv[]){ int arr[N][N]; memset(arr,0,sizeof(arr)); fill(arr); print(arr); return 0;}void print(int (*arr)[N]){ int i,j; for(i = 0; i < N; i++) { for(j = 0; j < N; j++) { printf("%3d",arr[i][j]); } printf("\n"); }}void fill(int (*arr)[N]){ int sum; int row,col; int num = 0; for(sum = 0; sum < 2 * N - 1; sum++) { if(sum % 2 == 0) { for(row = 0; row < N; row++) { col = sum - row; if(IS_LEGAL(row,col)) { arr[row][col] = ++num; } } }else { for(row = sum; row >=0; row--) { col = sum - row; if(IS_LEGAL(row,col)) { arr[row][col] = ++num; } } } }}