国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode題解:Battleships in a Board

2019-11-14 10:25:56
字體:
來源:轉載
供稿:網友

Given an 2D board, count how many battleships are in it. The battleships are rePResented with 'X's, empty slots are represented with '.'s. You may assume the following rules:

You receive a valid board, made of only battleships or empty slots.Battleships can only be placed horizontally or vertically. In other Words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example:

X..X...X...XIn the above board there are 2 battleships.

Invalid Example:

...XXXXX...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

思路:

簡單的思路是做搜索。但是考慮到每個船和每個船之間至少橫向縱向有一個空格,那么如果只考慮每艘船的右下角:

XX.X...X

這樣的話,右下角的X右邊和下面都是空格,每次碰到符合這個條件的X就認為碰到一個船,否則不管。

題解:

int countBattleships(const std::vector<std::vector<char>>& board) {    const int M = board.size();    const int N = board[0].size();    int numShips(0);    for(int i = 0; i < M; ++i) {        for(int j = 0; j < N; ++j) {            if (board[i][j] == 'X') {                numShips += ((i < M - 1 && board[i + 1][j] == '.') || (i == M - 1)) &&                            ((j < N - 1 && board[i][j + 1] == '.') || (j == N - 1));            }        }    }    return numShips;}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 榆社县| 根河市| 富阳市| 常山县| 昌吉市| 同心县| 晋城| 潼关县| 台湾省| 泰兴市| 株洲市| 南郑县| 宁陕县| 申扎县| 平舆县| 康平县| 当雄县| 临湘市| 碌曲县| 郓城县| 家居| 潍坊市| 博罗县| 廊坊市| 姚安县| 克山县| 梁山县| 安化县| 钦州市| 扬州市| 石阡县| 新民市| 广河县| 剑川县| 孝感市| 安国市| 农安县| 南康市| 南通市| 玉环县| 玉屏|