Skip to content

Commit e46ed55

Browse files
committed
Added the king's tour problem (without solution)
1 parent 4ca8da0 commit e46ed55

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

src/hard-google-king-tour/README.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Description
2+
3+
Good morning! Here's your coding interview problem for today.
4+
5+
This problem was asked by **Google**.
6+
7+
A knight's tour is a sequence of moves by a knight on a chessboard such that all squares are visited once.
8+
9+
Given `N`, write a function to return the number of knight's tours on an `N` by `N` chessboard.
10+
11+
# Source
12+
13+
Received by email from the [Daily Coding Problem](https://www.dailycodingproblem.com)

src/hard-google-king-tour/js/Idea.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Idea behind the solution
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"use strict";
2+
// TODO BE IMPLEMENTED
3+
4+
function isValid(i, j, n, visited) {
5+
return i >= 0 && j >= 0 && i < n && j < n && !visited[i][j];
6+
}
7+
8+
/**
9+
*
10+
* @param {Pos} currentPosition
11+
* @param {number} n
12+
* @param {boolean[][]} visited
13+
*/
14+
function solve(i, j, n, visited = new Array(n).fill(new Array(n))) {
15+
let hasEnded = true;
16+
17+
if (!isValid(i, j, n, visited)) return 0;
18+
19+
visited[i][j] = true;
20+
visited.forEach(row => {
21+
if (row.some(val => val === false)) hasEnded = false;
22+
});
23+
24+
if (hasEnded) return 1;
25+
26+
const possibilities = [];
27+
possibilities.push(solve(i + 1, j, n, visited.map(arr => arr.slice())));
28+
possibilities.push(solve(i - 1, j, n, visited.map(arr => arr.slice())));
29+
possibilities.push(solve(i, j + 1, n, visited.map(arr => arr.slice())));
30+
possibilities.push(solve(i, j - 1, n, visited.map(arr => arr.slice())));
31+
32+
return possibilities.reduce((total, current) => (total += current), 0);
33+
}
34+
35+
console.log(solve(0, 0, 4));

0 commit comments

Comments
 (0)