Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Created June 5, 2020 00:06
Show Gist options
  • Save germanescobar/05938f774e234543036728ebb285d26b to your computer and use it in GitHub Desktop.
Save germanescobar/05938f774e234543036728ebb285d26b to your computer and use it in GitHub Desktop.
/**
* @param {character[][]} board
* @return {number}
*/
var countBattleships = function(board) {
return countBattleshipsRec(board, 0, 0, false)
};
const mem = {}
function countBattleshipsRec(board, x, y, inAShip) {
let ships = 0;
if (board[x][y] === "X" && !mem[`${x}-${y}`]) {
if (!inAShip) {
ships++
inAShip = true
for (let i=y; i >= 0; i--) {
if (board[x][i] === "X") {
mem[`${x}-${i}`] = true
}
}
}
} else {
inAShip = false
}
if (x + 1 < board.length) {
ships += countBattleshipsRec(board, x+1, y, inAShip)
}
if (y + 1 < board[x].length) {
ships += countBattleshipsRec(board, x, y+1, inAShip)
}
return ships
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment