Guest User

Untitled

a guest
Jan 20th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>8クイーン問題</title>
  6. <style>
  7. body {
  8. background: #eeeeee;
  9. }
  10. div {
  11. background: #ffffff;
  12. width: 400px;
  13. padding: 10px;
  14. text-align: center;
  15. margin: 30px auto;
  16. }
  17. table {
  18. margin-left:auto;
  19. margin-right:auto;
  20. }
  21. td {
  22. width: 40px;
  23. height: 40px;
  24. text-align: center;
  25. border: 1px solid #cccccc;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <div>
  31. <h1>8クイーン問題</h1>
  32. <table id="board">
  33. </table>
  34. </div>
  35.  
  36. <script type="text/javascript">
  37. function createBoard(table) {
  38. for (let i = 0; i < N; i++) {
  39. let row = table.insertRow(-1);
  40. for (let j = 0; j < N; j++) {
  41. let cell = row.insertCell(-1);
  42. }
  43. }
  44. }
  45.  
  46. function putQueen(table, row, col) {
  47. table.rows[row].cells[col].textContent = 'Q';
  48. }
  49.  
  50. function removeQueen(table, row, col) {
  51. table.rows[row].cells[col].textContent = '';
  52. }
  53.  
  54. function search(table, i) {
  55. for (let k = 0; k < N; k++) {
  56. if (col[k] === FREE && upwd[i+k] === FREE
  57. && downwd[i-k+(N-1)] === FREE) {
  58. putQueen(table, i, k);
  59. col[k] = NOT_FREE;
  60. upwd[i+k] = NOT_FREE;
  61. downwd[i-k+(N-1)] = NOT_FREE;
  62. if (i == N-1) {
  63. return SUCCESS;
  64. }
  65. else {
  66. if (search(table, i+1) == SUCCESS) {
  67. return SUCCESS;
  68. }
  69. else {
  70. removeQueen(table, i, k);
  71. col[k] = FREE;
  72. upwd[i+k] = FREE;
  73. downwd[i-k+(N-1)] = FREE;
  74. }
  75. }
  76. }
  77. }
  78. return FAILURE;
  79. }
  80.  
  81. // Main
  82. const N = 8;
  83. const FREE = 0;
  84. const NOT_FREE = 1;
  85. const SUCCESS = 0;
  86. const FAILURE = 1;
  87.  
  88. let table = document.getElementById('board');
  89. createBoard(table);
  90. let col = [];
  91. for (let i = 0; i < N; i++) {
  92. col.push(FREE);
  93. }
  94. let upwd = []
  95. let downwd = [];
  96. for (let i = 0; i < 2*N-1; i++) {
  97. upwd.push(FREE); downwd.push(FREE);
  98. }
  99. search(table, 0);
  100. </script>
  101. </body>
  102. </html>
Add Comment
Please, Sign In to add comment