3 ms C++ solution with comments that make sense.


  • 0
    N
    public:
        int countBattleships(vector<vector<char>>& board) 
        {
            int len = board.size() * board[0].size();
            int rowSz = board[0].size();
            char prevChar = '.';
            int shipCnts = 0;
            for(int i = 0; i < len; i++)
            {
                if(board[i / rowSz][i % rowSz] == 'X')
                {
                    // count ships only when it appears first time.
                    // check horizontally by examining left(prevChar) and vertically by examining above
                    if(prevChar == '.' && (i < rowSz || board[i / rowSz - 1][i % rowSz] == '.'))
                        shipCnts++;
                }
                
                // when starts a new row, reset prevChar
                if(i % rowSz == rowSz - 1)
                    prevChar = '.';
                else
                    prevChar = board[i / rowSz][i % rowSz];
                
            }
            
            return shipCnts;
            
        }
    };``

Log in to reply
 

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