C++ simple 1 line


  • 0
    B

    many posts here consider the case of invalid board configuration

    for this problem, all board configurations are valid so we only need to count the top or left corner of each battleship

    class Solution {
    public:
        int countBattleships(vector<vector<char>>& board) {
            int count = 0;
            for(int i = 0; i < board.size(); i++)
                for(int j = 0; j < board[0].size(); j++)
                    if(board[i][j]=='X' 
                    && (i==0 || board[i-1][j]=='.') 
                    && (j==0 || board[i][j-1]=='.')) count++;
            return count;
        }
    };

Log in to reply
 

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