Java, very simple and easy understand code


  • 0
    D

    My idea is scan from left to right, line by line from up to down.
    we should check the up square and left square of current square
    if these two is both '.' and current square is 'X', we increase the ship number.

        public int countBattleships(char[][] board) 
        {
            int numOfShip = 0;
            
            for (int i = 0; i < board.length; i++)
            {
                for (int j = 0; j <board[0].length; j++)
                {
                    char c = board[i][j];
                    char up = i > 0? board[i - 1][j] : '.';
                    char left = j > 0? board[i][j - 1] : '.';
                    
                    if (c == 'X' && up == '.' && left == '.') numOfShip++;
                }
            }
            
            return numOfShip;
        }
    

Log in to reply
 

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