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 shape
1xN
(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 ...XIn the above board there are 2 battleships.
Invalid Example:
...X XXXX ...XThis 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) |
为了防止重复访问,用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; }
Keep it simple!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步