Advertisement
Guest User

Untitled

a guest
Feb 29th, 2020
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. // C program for Knight Tour problem
  2. #include<stdio.h>
  3. #include<stdbool.h>
  4. #define N 3
  5. void printSolution(int sol[N][N],int i,int j,int *count, int path[N*N],int);
  6.  
  7. bool isValid(int i, int j);
  8.  
  9. void printPath(int path[]);
  10.  
  11. /* A utility function to check if i,j are valid indexes
  12. for N*N chessboard */
  13.  
  14.  
  15.  
  16. int main(){
  17. int sol[N][N]={{1,2,3},{4,5,6},{7,8,9}};
  18. int path[N*2-1] = {0};
  19. int count =0;
  20. printSolution(sol,0,0,&count, path, 0);
  21. printf("%d",count);
  22. }
  23.  
  24. bool isValid(int i, int j){
  25.  
  26. return !((i>=N)||(i<0)||(j>=N)||(j<0));
  27.  
  28. }
  29.  
  30.  
  31. /* A utility function to print solution matrix sol[N][N] */
  32. void printSolution(int sol[N][N],int i,int j,int *count, int path[N*N], int currentPath)
  33. {
  34.  
  35. if((i==N-1)&&(j==N-1)){
  36. (*count)++;
  37. path[currentPath] = sol[i][j];
  38. printPath(path);
  39. return;
  40. }
  41.  
  42. path[currentPath] = sol[i][j];
  43.  
  44.  
  45. if(isValid(i, j+1))
  46. printSolution(sol, i, j+1, count, path, currentPath + 1);
  47.  
  48. if(isValid(i+1, j))
  49. printSolution(sol, i+1, j, count, path, currentPath + 1);
  50.  
  51. }
  52.  
  53.  
  54. void printPath(int path[N*2-1]){
  55.  
  56. int i=0;
  57. for(i =0; i<N*2-2; i++){
  58.  
  59. printf("(%d) -> ",path[i]);
  60.  
  61.  
  62. }
  63.  
  64. printf("(%d)\n", path[i]);
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement