Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="ja">
- <head>
- <meta charset="utf-8">
- <title>8クイーン問題</title>
- <style>
- body {
- background: #eeeeee;
- }
- div {
- background: #ffffff;
- width: 400px;
- padding: 10px;
- text-align: center;
- margin: 30px auto;
- }
- table {
- margin-left:auto;
- margin-right:auto;
- }
- td {
- width: 40px;
- height: 40px;
- text-align: center;
- border: 1px solid #cccccc;
- }
- </style>
- </head>
- <body>
- <div>
- <h1>8クイーン問題</h1>
- <table id="board">
- </table>
- </div>
- <script type="text/javascript">
- function createBoard(table) {
- for (let i = 0; i < N; i++) {
- let row = table.insertRow(-1);
- for (let j = 0; j < N; j++) {
- let cell = row.insertCell(-1);
- }
- }
- }
- function putQueen(table, row, col) {
- table.rows[row].cells[col].textContent = 'Q';
- }
- function removeQueen(table, row, col) {
- table.rows[row].cells[col].textContent = '';
- }
- function search(table, i) {
- for (let k = 0; k < N; k++) {
- if (col[k] === FREE && upwd[i+k] === FREE
- && downwd[i-k+(N-1)] === FREE) {
- putQueen(table, i, k);
- col[k] = NOT_FREE;
- upwd[i+k] = NOT_FREE;
- downwd[i-k+(N-1)] = NOT_FREE;
- if (i == N-1) {
- return SUCCESS;
- }
- else {
- if (search(table, i+1) == SUCCESS) {
- return SUCCESS;
- }
- else {
- removeQueen(table, i, k);
- col[k] = FREE;
- upwd[i+k] = FREE;
- downwd[i-k+(N-1)] = FREE;
- }
- }
- }
- }
- return FAILURE;
- }
- // Main
- const N = 8;
- const FREE = 0;
- const NOT_FREE = 1;
- const SUCCESS = 0;
- const FAILURE = 1;
- let table = document.getElementById('board');
- createBoard(table);
- let col = [];
- for (let i = 0; i < N; i++) {
- col.push(FREE);
- }
- let upwd = []
- let downwd = [];
- for (let i = 0; i < 2*N-1; i++) {
- upwd.push(FREE); downwd.push(FREE);
- }
- search(table, 0);
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment