C# - count only top left cell of battleship - simple 1 pass


  • 1
        public int CountBattleships(char[,] board) 
        {
            int rows = board.GetLength(0);
            int cols = board.GetLength(1);
            int count = 0;
            
            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < cols; c++)
                {
                    // if this is a top left cell of a battleship then count this ship
                    // each ship will only be counted once
                    if (board[r,c] == 'X'
                        && (r == 0 || board[r-1,c] == '.') 
                        && (c == 0 || board[r,c-1] == '.'))
                    {
                        count++;
                    }
                }
            }
            
            return count;
        }
    

Log in to reply
 

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