# Share my 7-line code, 1-line core code, 3ms, super easy

• No need to modify the input matrix.

``````public int countBattleships(char[][] board) {
int count = 0;
for(int i=0;i<board.length;i++)
for(int j=0;j<board[0].length;j++)
if(board[i][j]=='X' && (i==0 || board[i-1][j]!='X') && (j==0 || board[i][j-1]!='X')) count++;
return count;
}
``````

• Though the code is succinct but it actually takes 6ms to run.

• @YuTingLiu to make sure I understand, this is counting the starting corners of each ship?

• @betts
Not the starting corner. It can be any "1" for a ship.

• @betts
Not the starting corner. It can be any "1" for a ship.

Well, apparently, the following condition

``````(i==0 || board[i-1][j]!='X') && (j==0 || board[i][j-1]!='X')
``````

is true only for upper left corner of a battleship. If counting for any `'X'` on a battleship, there will be many duplicates.

• are you using Nana Komatsu as the profile pictures?

• Brilliant solution!

• I write the same code in C++ as yours, lol

``````    int countBattleships(vector<vector<char>>& board) {
int count=0;
for(int i=0;i<board.size();i++)
for(int j=0;j<board[0].size();j++)
if(board[i][j]=='X'&&(i==0||board[i-1][j]!='X')&&(j==0||board[i][j-1]!='X')) count++;
return count;
}
``````

• @Zura Looks like so according to Google.

• Briliant solution! Huge respect :)

• This post is deleted!

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