Skip to content

Instantly share code, notes, and snippets.

@davidsa
Created October 17, 2019 15:42
Show Gist options
  • Save davidsa/283326e3fbde47bffd0b1813f52f4825 to your computer and use it in GitHub Desktop.
Save davidsa/283326e3fbde47bffd0b1813f52f4825 to your computer and use it in GitHub Desktop.
var table = [
[0, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
function findBoat(boat, grid, i, j, direction) {
//End of boat
if (grid[i][j] === 0) {
return
}
// Down
if (grid[i + 1] && grid[i + 1][j] && grid[i + 1][j] === 1) {
boat.push([i + 1, j])
findBoat(boat, grid, i + 1, j);
grid[i + 1][j] = 0
return
}
// Right
if (grid[i] && grid[i][j + 1] && grid[i][j + 1] === 1) {
boat.push([i, j + 1])
findBoat(boat, grid, i, j + 1);
grid[i][j + 1] = 0
return
}
//Diagonal right down
if (grid[i + 1] && grid[i + 1][j + 1] && grid[i + 1][j + 1] === 1) {
boat.push([i + 1, j + 1])
findBoat(boat, grid, i + 1, j + 1);
grid[i + 1][j + 1] = 0
return
}
//Diagonal left down
if (grid[i + 1] && grid[i + 1][j - 1] && grid[i + 1][j - 1] === 1) {
boat.push([i + 1, j - 1])
findBoat(boat, grid, i + 1, j - 1);
grid[i + 1][j - 1] = 0
return
}
}
function findShips(grid) {
var results = []
grid.forEach((row, i) => {
row.forEach((pos, j) => {
if (pos === 1) {
var boat = []
boat.push([i, j])
findBoat(boat, grid, i, j);
results.push(boat);
}
})
})
console.log(results)
}
findShips(table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment