One pass O(1) space C++ code


  • 0
    G
    class Solution {
    public:
    
        int countBattleships(vector<vector<char>>& board) 
        {
            int Total = 0;
            
            for(int i = 0; i < board.size(); ++i)
            {
                for(int j = 0; j < board[i].size(); ++j)
                {
                    if(board[i][j] == 'X')
                    {
                        //
                        // look up and to the left to see if we discovered
                        // this ship before.
                        //
                        if((i == 0 || (board[i - 1][j] != 'X')) &&
                            ((j == 0) || (board[i][j - 1] != 'X')))
                            {
                                Total++;
                            }
                    }
                }
            }
            
            return (Total);
        }
        
    };

Log in to reply
 

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