---
# System prepended metadata

title: 0419. Battleships in a Board
tags: [Leetcode, DFS, Medium]

---

# 0419. Battleships in a Board
###### tags: `Leetcode` `Medium` `DFS`
Link: https://leetcode.com/problems/battleships-in-a-board/
## 思路
其实这题跟[0562. Longest Line of Consecutive One in Matrix](https://hackmd.io/56Zexs7iTzG5ZBjUgg2RkQ)有点像
但是不完全一样，这题不需要用dfs
一样的地方在于如果左边和上边已经是X了 说明这个点已经被count过了不要再count了(因为不会有两个battle ship在一块)
## Code
```java=
class Solution {
    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]=='.') continue;
                if(i-1>=0 && board[i-1][j]=='X') continue;
                if(j-1>=0 && board[i][j-1]=='X') continue;
                count++;
            }
        }
        return count;
    }
}
```