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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

LeetCode題解:Battleships in a Board

2019-11-14 10:32:24
字體:
供稿:網(wǎng)友

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就認(rèn)為碰到一個船,否則不管。

題解:

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;}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 靖边县| 古蔺县| 浦县| 珠海市| 渝北区| 韩城市| 德兴市| 南木林县| 城市| 南川市| 蒙自县| 旅游| 英吉沙县| 奉化市| 育儿| 民勤县| 绥江县| 南昌县| 盐城市| 伊春市| 南部县| 兰西县| 体育| 台州市| 贞丰县| 古丈县| 元阳县| 盐津县| 衡阳市| 新龙县| 沙洋县| 洛宁县| 光山县| 鹤峰县| 金堂县| 龙泉市| 广昌县| 淮南市| 扎兰屯市| 明光市| 忻州市|