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

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

LeetCode題解:Battleships in a Board

2019-11-14 09:58:51
字體:
來源:轉載
供稿:網友

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安龙县| 汉源县| 盐山县| 鄂温| 昌江| 科技| 登封市| 尖扎县| 客服| 镶黄旗| 砚山县| 宜兰市| 建平县| 灌云县| 永善县| 柳江县| 灵武市| 黄大仙区| 电白县| 卫辉市| 博客| 临安市| 昂仁县| 通州市| 汉源县| 施甸县| 澳门| 汶上县| 铜鼓县| 玉龙| 渭南市| 雷州市| 沐川县| 博爱县| 平谷区| 水城县| 黄大仙区| 呼伦贝尔市| 安国市| 梅河口市| 旺苍县|