Concise c# solution


  • 1
    M
    public class Solution {
    public int CountBattleships(char[,] board) {
        int r = 0;
        for(int i = 0; i < board.GetLength(0); i++) {
            for(int j = 0; j < board.GetLength(1); j++) {
                if(board[i,j] == 'X' &&
                    (i == 0 || board[i-1,j] == '.') &&
                    (j == 0 || board[i,j-1] == '.')
                ) {
                    r++;        
                }
            }
        }
        return r;
    }
    

    }


  • 0
    M
    This post is deleted!

  • 0
    M

    My solution is almost identical, with a little more commentary:

        public int CountBattleships(char[,] board) {
            
            int noOfShips = 0;
            int noOfRows = board.GetLength(0);
            int noOfColumns = board.GetLength(1);
            
            // This algorithm counts, not each point, but the bottom-right most point of every ship.
            // In other words, if the ship continues in the next column, then count it later;
            // and if it continues in the next row, then count it later.
            // That way, we only ever count the last iteration in which we encounter the ship on the board.
            for (int row = 0; row < noOfRows; row++)
            {
                for (int column = 0; column < noOfColumns; column++)
                {
                    if (board[row, column] == 'X')
                    {
                        bool continuesInNextRow = row + 1 < noOfRows && board[row + 1, column] == 'X';
                        bool continuesInNextColumn = column + 1 < noOfColumns && board[row, column + 1] == 'X';
                        
                        if (!continuesInNextRow && !continuesInNextColumn)
                        {
                            noOfShips++;
                        }
                    }
                }
            }
            return noOfShips;
        }
    

Log in to reply
 

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