首页 > 代码库 > [LeetCode]419 Battleships in a Board(暴力,dfs)

[LeetCode]419 Battleships in a Board(暴力,dfs)

题目链接:https://leetcode.com/problems/battleships-in-a-board/?tab=Description

题意:问平面上有多少条船,船是1*n或者n*1的,并且不相交。

最简单的想法就是直接dfs,但是看到题目里有一个思考,那就是不修改平面并且空间O(1)的one-pass。

这时候就想到应该是遍历所有船的左上角的端点,统计就行了。很简单。

 1 public class Solution {
 2     public int countBattleships(char[][] board) {
 3         int ret = 0;
 4         for (int i = 0; i < board.length; i++) {
 5             for (int j = 0; j < board[0].length; j++) {
 6                 if (board[i][j] == X && (i == 0 || board[i-1][j] == .) && (j == 0 || board[i][j-1] == .)) {
 7                     ret++;
 8                 }
 9             }
10         }
11         return ret;
12     }
13 }

 

DFS的代码

 1 class Solution {
 2 public:
 3     const int dx[5] = {0, 0, 1, -1};
 4     const int dy[5] = {1, -1, 0, 0};
 5     int ret;
 6     int ok(vector<vector<char>>& board, int x, int y) {
 7         return x < board.size() && y < board[0].size();
 8     }
 9 
10     void dfs(vector<vector<char>>& board, int x, int y) {
11         board[x][y] = .;
12         for(int i = 0; i < 4; i++) {
13             int xx = x + dx[i];
14             int yy = y + dy[i];
15             if(ok(board, xx, yy) && board[xx][yy] == X) {
16                 dfs(board, xx, yy);
17             }
18         }
19     }
20 
21   int countBattleships(vector<vector<char>>& board) {
22       ret = 0;
23       for(int i = 0; i < board.size(); i++) {
24           for(int j = 0; j < board[i].size(); j++) {
25               if(board[i][j] == X) {
26                   dfs(board, i, j);
27                   ret++;
28               }
29           }
30       }
31       return ret;
32   }
33 };

 

[LeetCode]419 Battleships in a Board(暴力,dfs)