Created
February 24, 2019 12:32
-
-
Save 4skinSkywalker/a12b503ddafe65d1a0957c5372610ae6 to your computer and use it in GitHub Desktop.
The fifth hardest challenge listed in the “easy” section of Coderbyte.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closestEnemy(matrix) { | |
let length = matrix.length | |
let isValid = matrix.some(v => v.includes(2)) | |
if (!isValid) return -1 | |
let startingPoint | |
for (let i = 0; i < length; i++) { | |
for (let j = 0; j < length; j++) { | |
if (matrix[i][j] === 1) { | |
startingPoint = [i, j] | |
} | |
} | |
} | |
let directions = [[-1,0],[0,1],[1,0],[0,-1]] | |
let count = 1 | |
let queue = [startingPoint] | |
while (queue.length > 0) { | |
let [y, x] = queue.pop() | |
for (let dir of directions) { | |
let [dy, dx] = dir | |
let newY = y + dy >= 0 ? y + dy % length : length - 1 | |
let newX = x + dx >= 0 ? x + dx % length : length - 1 | |
if (matrix[newY][newX] === 2) return count | |
queue.push([newY, newX]) | |
} | |
count++ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment