#include #include #define N 4 #define M 7 /* Structure to represent a cell in the n x n mess */ typedef struct { int row, col; } loc; /* We order the cells lexicographically, first with respect to the row number, and then with respect to the column number. This function returns the location next to p. If p is invalid or the last cell in the grid, an invalid location is returned. */ loc nextloc ( int n, loc p ) { if ((p.row < 0) || (p.col < 0)) return (loc){-1,-1}; if ((p.row >= n) || (p.col >= n)) return (loc){-1,-1}; if ((p.row == n-1) && (p.col == n-1)) return (loc){-1,-1}; if (p.col == n-1) return (loc){p.row+1,0}; return (loc){p.row,p.col+1}; } /* Check whether two cells p1 and p2 are adjacent (that is, share an edge). This function assumes that p1 and p2 are different. */ int adjacent ( loc p1, loc p2 ) { if (p1.row == p2.row) { if ((p1.col == p2.col+1) || (p2.col == p1.col+1)) return 1; return 0; } if (p1.col == p2.col) { if ((p1.row == p2.row+1) || (p2.row == p1.row+1)) return 1; return 0; } return 0; } /* A currently stores k mutually non-adjacent cells. A new location p is intended to be added. The addition is valid if and only if p is not adjacent to any of the k cells already present in A. */ int valid ( loc A[], int k, loc p ) { int i; for (i=0; i= 0) { /* For all possibilities of p */ if (valid(A,k,p)) { /* If the insertion of p in A[] is valid */ A[k] = p; arrange(A,n,m,k+1,serno); /* Recursive call on k+1 chosen cells */ } p = nextloc(n,p); /* Step through the next value of p */ } } int main ( int argc, char *argv[] ) { int n, m, serno = 0; loc *A; if (argc > 1) n = atoi(argv[1]); else n = N; if (argc > 2) m = atoi(argv[2]); else m = M; A = (loc *)malloc(m * sizeof(loc)); arrange(A,n,m,0,&serno); exit(0); }