美文网首页
419. Battleships in a Board

419. Battleships in a Board

作者: matrxyz | 来源:发表于2018-01-16 11:42 被阅读0次

https://leetcode.com/problems/battleships-in-a-board/description/

Solution:

思路:
限定了不会有相邻的两个战舰的存在,有了这一点限制,那么我们只需要遍历一次二维数组就行了,只要找出战舰的起始点。所谓的战舰起始点,就是为X的点,而且该点的上方和左边的点不能为X,所以我们只要找出所有满足这个条件的点即可

Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    public int countBattleships(char[][] board) {
        int m = board.length;
        if (m==0) return 0;
        int n = board[0].length;
        
        int count=0;
        
        for (int i=0; i<m; i++) {
            for (int j=0; j<n; j++) {
                if (board[i][j] == '.') continue;
                if (i > 0 && board[i-1][j] == 'X') continue;
                if (j > 0 && board[i][j-1] == 'X') continue;
                count++;
            }
        }
        
        return count;
    }
}

相关文章

网友评论

      本文标题:419. Battleships in a Board

      本文链接:https://www.haomeiwen.com/subject/urksoxtx.html