419. Battleships in a Board

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

由X和.组成的二维格子统计合法的X:和上下左右其它的X至少隔开一个.。从左上到右下遍历直接对每个X检查横和下是不是X,是就不合法。虽然这题看上去简单的过分,但题目描述很故意搞的很复杂,顺着题目描述想容易被绕进去。

/*
 * @lc app=leetcode id=419 lang=cpp
 *
 * [419] Battleships in a Board
 */

// @lc code=start
class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        const int M = board.size(), N = M == 0 ? 0 : board[0].size();
        int res = 0;
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                if (board[i][j] != 'X') continue;
                if (i + 1 < M && board[i + 1][j] == 'X') continue;
                if (j + 1 < N && board[i][j + 1] == 'X') continue;
                ++res;
            }
        }
        return res; 
    }
};
// @lc code=end

Last updated