#include < stdio.h>
#define UP 0
#define LEFT 1
#define DOWN 2
#define RIGHT 3
int getele(int *arr, int x, int y, int size) {
int pos=(x*size)+y;
return arr[pos];
}
int setele(int *arr, int x, int y, int data, int size) {
int pos=(x*size)+y;
arr[pos]=data;
}
void setspiral_worker(int *arr, int x, int y, int data, int size, int dir) {
if(data==1)
setele(arr, x, y, data, size);
else {
setele(arr, x, y, data, size);
dir=check_change_dir(arr, x, y, size, dir);
if (dir == UP) {
x--;
} else if (dir == LEFT) {
y--;
} else if (dir == DOWN) {
x++;
} else if (dir == RIGHT) {
y++;
}
setspiral_worker(arr, x, y, data-1, size, dir);
}
}
void setspiral_driver(int *arr, int size) {
setspiral_worker(arr, size-1, size-1, size*size, size, UP);
}
int check_change_dir(int *arr, int x, int y, int size, int dir) {
if (dir == UP) {
x--;
} else if (dir == LEFT) {
y--;
} else if (dir == DOWN) {
x++;
} else if (dir == RIGHT) {
y++;
}
if (x>=0 && x<=size-1 && y>=0 && y<=size-1
&& getele(arr, x, y, size) == 0)
return dir;
else
return (dir+1)%4;
}
int main() {
int oper=UP;
int size;
int i,j;
int *matrix;
printf("Enter the size:");
scanf("%d", &size);
matrix=malloc(size*size);
for(i=0; i < size ;i++)
for(j=0; j < size;j++)
setele(matrix, i, j, 0, size);
setspiral_driver(matrix, size);
for(i=0; i < size;i++) {
for(j=0; j < size;j++)
printf("%4d\t",getele(matrix, i, j, size));
printf("\n");
}
return 0;
}
Wednesday, November 07, 2007
Spiral Matrix Program
My Spiral Matrix Program
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment