Knight's shortest path
O(1) solution
HTML
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
CSS
.board {
display: inline-block;
}
table {
border-collapse: collapse
}
td {
padding: 0;
text-align: center;
vertical-align: middle;
width: 1em
}
tr {
height: 1em;
}
.diagonal {
background-color: red;
}
.special {
background-color: yellow;
}
.vertical {
border-left: 2px solid black;
border-right: 2px solid black;
}
.vertical.bottom {
border-bottom: 2px solid black;
}
.vertical.top {
border-top: 2px solid black;
}
.horizontal {
border-top: 2px solid black;
border-bottom: 2px solid black;
}
.horizontal.left {
border-left: 2px solid black;
}
.horizontal.right {
border-right: 2px solid black;
}
.primary-diagonal {
background-color: red;
}
.primary-diagonal div {
transform: rotate(-45deg);
}
.secondary-diagonal {
background-color: lightblue;
}
.secondary-diagonal div {
transform: rotate(-45deg);
}
/* This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/). */
/* CSS specs as packaged in the D3 library (d3js.org). Please see license at http://colorbrewer.org/export/LICENSE.txt...
JavaScript
//
// [2017-05-22] Challenge #316 [Easy] Knight's Metric
// https://www.reddit.com/r/dailyprogrammer/comments/6coqwk/20170522_challenge_316_easy_knights_metric/
//
// Demo at https://plnkr.co/edit/c6DBp8lF96R6U2huIltF?p=preview
//
// A knight piece in chess can only make L-shaped moves. Specifically, it can only move x steps to the right and y steps up if (x,y) is one of:
// (-1,-2) ( 1,-2) (-1, 2) ( 1, 2)
// (-2,-1) ( 2,-1) (-2, 1) ( 2, 1)
// Write a program, that, given a square (x,y), returns how many moves it takes a knight to reach that square starting from (0,0).
//
// by Kory Becker
// http://primaryobjects.com
//
var KnightManager = {
maxDepth: 5,
moves: [
{ x: -1, y: -2 },
{ x: 1, y: -2 },
{ x: -1, y: 2 },
{ x: 1, y: 2 },
{ x: -2, y: -1 },
{ x: 2, y: -1 },
{ x: -2, y: 1 },
{ x: 2, y: 1 }
],
solve: function(start, dest) {
var result = null;
var fringe = [ { position: start, depth: 0, history: [] } ];
while (fringe.length) {
var current = fringe.pop();
// Check for goal.
if (current.position.x === dest.x && current.position.y === dest.y) {
result = current;
break;
}
else {
// Add child states to fringe.
KnightManager.moves.forEach(function(move) {
var state = { position: { x: current.position.x + move.x, y: current.position.y + move.y }, depth: current.depth + 1, history: JSON.parse(JSON.stringify(current.history)) };
state.history.push(current.position);
if (state.depth <= KnightManager.maxDepth) {
fringe.push(state);
}
});
}
}
return result;
}
};
console.log((KnightManager.solve({ x: 0, y: 0 }, { x: 3, y: 7 }));