Home > Uncategorized > recursively print out a clockwise matrix element, spiral

recursively print out a clockwise matrix element, spiral


Here is a program using recursive to print out a clockwise matrix element like this:
   1     2     3     4     5     6     7     8     9    10 
  36    37    38    39    40    41    42    43    44    11 
  35    64    65    66    67    68    69    70    45    12 
  34    63    84    85    86    87    88    71    46    13 
  33    62    83    96    97    98    89    72    47    14 
  32    61    82    95   100    99    90    73    48    15 
  31    60    81    94    93    92    91    74    49    16 
  30    59    80    79    78    77    76    75    50    17 
  29    58    57    56    55    54    53    52    51    18 
  28    27    26    25    24    23    22    21    20    19 

#include
#include
#include

// Print clockwise matrix element, in C
// http://www.VictorFang.com
// 20100412

// n : current recursive call’s matrix size
// x, y: start pt in this round
// start: first value to set in the matrix
void setmatrix(int** m, int x, int y, int start, int n){

    int i,j;

    // for even number
    if(n<=0)
        return;

    // for odd number
    if(n==1){
        m[x][y] = start;
        return;
        }

   
    for(i = x; i
        m[y][i] = start++; // upper, to the right

    for(j = y; j < y+n-1; j++ )
        m[j][x+n-1] = start++; // right , downward

    for(i=x+n-1; i>x; i–)
        m[x+n-1][i] = start++; // lower, to the left

    for(j = y+n-1; j>y; j–)
        m[j][x] = start++; // left, upward

    // recursive call the next inner cycle
    setmatrix(m, x+1, y+1, start, n-2);

    }

void main() {

    FILE *fp;

    int n = 10; // size of matrix, 5×5;
    int i , j;

    int** matrix = (int **) malloc( n*sizeof(int *) );

    for(i = 0; i
        matrix[i] = (int *) malloc(n*sizeof(int));

    for(i = 0; i
        for(j = 0; j
            matrix[i][j] = 0;

    // do the job!
    setmatrix(matrix, 0 , 0, 1, n);

    char fstr[10] ;

    sprintf(fstr, “%d.txt”, n);

    fp = fopen(fstr, “w”);

    for(i = 0; i
            for(j = 0; j
                printf(“%4d  “, matrix[i][j]);
                fprintf(fp, “%4d  “, matrix[i][j]);
                }
            printf(“\n”);
            fprintf(fp, “\n”);
        }

    fclose(fp);
    printf(“Result is written into file: %s\n”, fstr);

    getchar();

    }

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: