博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
419. Battleships in a Board
阅读量:4590 次
发布时间:2019-06-09

本文共 2289 字,大约阅读时间需要 7 分钟。

Given an 2D board, count how many different 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...X
In the above board there are 2 battleships.

Invalid Example:

...XXXXX...X
This is not a valid board - as battleships will always have a cell separating between them.

Your algorithm should not modify the value of the board.

考察的是深度优先遍历的使用

思路:

通过DFS遍历四个方向 

(i - 1, j)
(i, j - 1) (i, j) (i, j + 1)
(i + 1, j)  
X的一堆区域(都是X)就是一个战舰,求一共有多少战舰。

为了防止重复访问,用visited数组标记下已访问的结点

解答:

#include 
#include
using namespace std;class Solution {public: void dfs(vector
>& board, int i, int j) { visited[i][j] = true; //left if (i >= 0 && i < n && j - 1 >= 0 && j - 1 < m && !visited[i][j - 1] && board[i][j - 1] == 'X') { dfs(board, i, j - 1); } //right if (i >= 0 && i < n && j + 1 >= 0 && j + 1 < m && !visited[i][j + 1] && board[i][j + 1] == 'X') { dfs(board, i, j + 1); } //top if (i - 1 >= 0 && i - 1 < n && j >= 0 && j < m && !visited[i - 1][j] && board[i - 1][j] == 'X') { dfs(board, i - 1, j); } //bottom if (i + 1 >= 0 && i + 1 < n && j >= 0 && j < m && !visited[i + 1][j] && board[i + 1][j] == 'X') { dfs(board, i + 1, j); } } int countBattleships(vector
>& board) { n = board.size(); m = board[0].size(); num = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { visited[i][j] = false; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (board[i][j] == 'X' && !visited[i][j]) { num++; dfs(board, i, j); } } } return num; }private: int n; int m; int num; bool visited[1000][1000];};int main(){ Solution s; vector
>vec{ { 'X', '.', '.', 'X' }, { '.', '.', '.', 'X' }, { '.', '.', '.', 'X' } }; cout << s.countBattleships(vec); return 0;}

转载于:https://www.cnblogs.com/lgh1992314/p/6616337.html

你可能感兴趣的文章
内存对齐
查看>>
HTML及资源是如何load的
查看>>
虚拟机apache启动
查看>>
【Linux】Centos下安装ffmpeg
查看>>
VSCode使用随笔
查看>>
MySQL 常用命令
查看>>
nginx FastCGI配置 No input file specified
查看>>
iOS - 拓展
查看>>
Windows命令远程执行工具Winexe
查看>>
XamarinAndroid组件教程RecylerView动画组件使用动画(3)
查看>>
linux vim 配置 go 开发环境
查看>>
week 6 CORS
查看>>
Openstack Neutron:二层技术和实现
查看>>
组合设计模式
查看>>
第十五部分_Struts2.1拦截器深度剖析、异常处理
查看>>
[codevs1286]郁闷的出纳员
查看>>
Python匿名函数详解
查看>>
python面向对象(六)之元类
查看>>
quartz.net插件类库封装(含源码)
查看>>
package.json中 npm依赖包版本前的符号的意义
查看>>