Very Simple, Very Clear - 3ms


  • 0
    M

    Only count an 'X' if there is no other to its left or above it. This means it's the first 'X' of a horizontal or vertical ship.

        int countBattleships(vector<vector<char>>& board) {
            if (board.empty() || board[0].empty()) return 0;
            
            int res = 0;
            for (int i = 0; i < board.size(); ++i) {
                for (int j = 0; j < board[0].size(); ++j) {
                    bool left = i > 0 && board[i-1][j] == 'X';
                    bool up = j > 0 && board[i][j-1] == 'X';
                    
                    res += board[i][j] == 'X' && !up && !left;
                }
            }
            
            return res;
        }
    

Log in to reply
 

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