419. Battleships in a Board

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

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 shape1xN(1 row, N columns) orNx1(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:

...X
XXXX
...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 <iostream>
#include <vector>
using namespace std;

class Solution {
public:
	void dfs(vector<vector<char>>& 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<vector<char>>& 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<vector<char> >vec{ { 'X', '.', '.', 'X' }, { '.', '.', '.', 'X' }, { '.', '.', '.', 'X' } };
	cout << s.countBattleships(vec);

	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值