Simple Java solution fulfill follow up. Using one for loop.


  • 0
    F

    Use index / width and index % width to go through the loop. Count the valid battleship if no battleship left or above it.

    public class Solution {
        public int countBattleships(char[][] board) {
            int count = 0,L = board.length,W = board[0].length;
            for(int index = 0;index<L*W;index++){
                if(board[index / W][index % W] == '.') continue;
                if(index>=W && (board[(index-W)/ W][index % W] == 'X')) continue;
                if(index % W !=0 && (board[index / W][(index-1) % W] == 'X')) continue;
                count++;
            }
            return count;
        }
    }   
    

Log in to reply
 

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