Simple Javascript Solution


  • 0
    A

    Single pass, looking at each row. The trick here is to look for the "front tip" of the ship as your individual ship identifier. The "front tip" is the part of the ship where there is no "X" to the left AND top.

    Note that to traverse the board] representation of the grid, you have to have a nested loop of y first then x. When accessing the board, the first [] is the y and the inner [] is the x.

    '''
    var countBattleships = function(board) {
    var count = 0;

    console.log(board[0].length);
    console.log(board.length);
    for(var y = 0; y < board.length; y++){
        for(var x = 0; x < board[0].length; x++){
            var character = board[y][x];
            console.log('looking at ' + x + ',' + y);
            if(character == "X"){
                if((x === 0 || board[y][x-1] !== "X") && (y === 0 || board[y-1][x] !== "X")){
                    count++;
                }
            }
        }
    }
    
    return count;
    

    };
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.