Advertisement
Guest User

n-knights

a guest
Nov 8th, 2013
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. long int nrBoards;
  5.  
  6. typedef struct {
  7.   int board[8][8];
  8. } chessboard;
  9.  
  10.  
  11. int maxN;
  12.  
  13.  
  14. int checkPlace(int y, int x, chessboard boards) {
  15.     if (boards.board[y - 2][x - 1] == 1) {
  16.       return 0;
  17.     }
  18.     if (boards.board[y - 1][x - 2] == 1) {
  19.       return 0;
  20.     }
  21.     if (boards.board[y - 2][x + 1] == 1) {
  22.       return 0;
  23.     }
  24.     if (boards.board[y - 1][x + 2] == 1) {      
  25.       return 0;
  26.     }
  27.     if (boards.board[y + 1][x + 2] == 1) {
  28.       return 0;
  29.     }
  30.     if (boards.board[y + 1][x - 2] == 1) {      
  31.       return 0;
  32.     }
  33.     if (boards.board[y + 2][x - 1] == 1) {
  34.       return 0;
  35.     }
  36.     if (boards.board[y + 2][x + 1] == 1) {
  37.       return 0;
  38.     }
  39.     return 1;
  40. }
  41.    
  42. void printBoard(chessboard boards) {
  43.   int i, j;
  44.   for(i = 0; i < 8; i++) {
  45.     for(j = 0; j < 8; j++) {
  46.       printf("%d ", boards.board[i][j]);
  47.       if (j == 7) {
  48.       printf(" %d", i);
  49.       }
  50.     }
  51.  
  52.   printf("\n");
  53.   if (i == 7) {
  54.     printf("\n0 1 2 3 4 5 6 7\n");
  55.   }
  56.   }
  57.  
  58.   printf("\n");
  59. }
  60.  
  61.  
  62.  
  63. void placeKnight(int y, int x, int n, int f, chessboard boards) {
  64.   /* base case */
  65.   if ((n <= 0)) {
  66.     printBoard(boards);
  67.     nrBoards++;
  68.     printf("nrBoards = %ld\n\n", nrBoards);
  69.     return;
  70.   }
  71.  
  72.   if ((x > 7) && (y < 7)) {
  73.   x = 0;
  74.   y++;
  75.   }
  76.   if ((x > 7) && (y == 7)) {
  77.     return;
  78.   }
  79.   /* recursive case */
  80.      if ((f >= n)) {
  81.     placeKnight(y, x + 1, n, f - 1, boards);
  82.      }
  83.      if (checkPlace(y, x, boards) == 1) {
  84.      boards.board[y][x] = 1;
  85.     placeKnight(y, x + 1, n - 1, f - 1, boards);
  86.      }
  87. }
  88.  
  89.  
  90.    
  91.    
  92. int main(int argc, char* argv[]){
  93.   chessboard boards;
  94.   int i, j, n;
  95.   n = 0;
  96.   scanf("%d", &maxN);
  97.   printf("start");
  98.  
  99.   for(i = 0; i < 8; i++) {
  100.     for(j = 0; j < 8; j++) {
  101.       boards.board[i][j] = 0;
  102.     }
  103.   }
  104.   placeKnight(0, 0, maxN, 64, boards);
  105.   return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement