Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. //Nome: Hiago Rafael de Souza
  2. //Curso: Engenharia de computação UFSCar
  3.  
  4.  
  5. #include <stdio.h>
  6. #include<stdbool.h>
  7.  
  8. int tabuleiro[13][13]; //tamanho do tabuleiro
  9. int solucoes=0; //numero de solucoes
  10.  
  11.  
  12.  
  13. bool livre(int N, int lin, int col) // verifica se a posição está segura para a rainha
  14. {
  15. int i, j;
  16. for(i=0; i<N; i++) // verifica a linha
  17. {
  18. if(tabuleiro[lin][i]==1)
  19. return false;
  20. }
  21.  
  22. for(i=0; i<N; i++) //verifica a coluna
  23. {
  24. if(tabuleiro[i][col]==1)
  25. return false;
  26. }
  27.  
  28.  
  29. for(i=lin, j=col; i>=0 && j>=0; i--, j--) //verifica as diagonais
  30. {
  31. if(tabuleiro[i][j]==1)
  32. return false;
  33. }
  34. for(i=lin, j=col; i<N && j<N; i++, j++)
  35. {
  36. if(tabuleiro[i][j]==1)
  37. return false;
  38. }
  39.  
  40. for(i=lin, j=col; i>=0 && j<N; i--, j++)
  41. {
  42. if(tabuleiro[i][j] == 1)
  43. return false;
  44. }
  45. for(i=lin, j=col; i<N && j>=0; i++, j--)
  46. {
  47. if(tabuleiro[i][j]==1)
  48. return false;
  49. }
  50.  
  51. return true; //caso todas as posições estejam seguras, a rainha é alocada
  52. }
  53.  
  54. void executar(int N, int col)
  55. {
  56. if(col==N)
  57. {
  58. solucoes++; //soma +1 nas soluções se estiver livre
  59. return;
  60. }
  61.  
  62. for(int i=0; i<N; i++)
  63. {
  64. if(livre(N,i,col)) //chama a função para verificar
  65. {
  66. tabuleiro[i][col] = 1; // aloca a rainha (1 para true)
  67. executar(N,col+1); //utiliza recursividade para chamar novamente
  68. tabuleiro[i][col]=0;
  69. }
  70. }
  71. }
  72.  
  73. int main()
  74. {
  75.  
  76. int N; //numero n
  77. scanf("%d",&N); //recebe o numero desejado
  78. executar(N, 0); //chama a função
  79. printf("%d",solucoes); //imprime o resultado
  80.  
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement