LeetCode419甲板上的战舰

207 阅读1分钟

🍀甲板上的战舰

描述:

 # 给你一个大小为 m x n 的矩阵 board 表示甲板,其中,每个单元格可以是一艘战舰 'X' 或者是一个空位 '.' ,返回在甲板 board 上放置的 战舰 的数量。战舰 只能水平或者垂直放置在 board 上。换句话说,战舰只能按 1 x k(1 行,k 列)或 k x 1(k 行,1 列)的形状建造,其中 k 可以是任意大小。两艘战舰之间至少有一个水平或垂直的空位分隔 (即没有相邻的战舰)。

image.png

思考:

这道题意思是看甲板上有多少战舰(谁家战舰放甲板上= =),甲板之间呢又是不在一块的,就类似于数据结构中让你求出图有多少连通分量!类似解决办法一般有三种:DFS、BFS以及并查集!

实现:

 public class Solution {
 ​
     public int countBattleships(char[][] board) {
 ​
         int m = board.length;
         int n = board[0].length;
         int count = 0;
 ​
         for (int i = 0; i < m; i++) {
             for (int j = 0; j < n; j++) {
                 if (board[i][j] == 'X'){
                     board[i][j] = '.';
                     // 右边找
                     for (int k = j + 1; k < n && board[i][k] == 'X'; k++) {
                         board[i][k] = '.';
                     }
                     // 下边找
                     for (int k = i + 1; k < m && board[k][j] == 'X'; k++) {
                         board[k][j] = '.';
                     }
                     count++;
                 }
             }
         }
         return count;
     }
 ​
 }

测试一下!

image.png

大佬的代码:

 class Solution {
 public:
     int m, n;
     int countBattleships(vector<vector<char>>& board) {
         m = board.size();
         n = board[0].size();
 ​
         int cnt = 0;
         for (int i = 0; i < m; i++) {
             for (int j = 0; j < n; j++) {
                 if (board[i][j] == '.' || board[i][j] == 'Y') continue;
                 dfs(board, i, j);
                 cnt++;
             }
         }
 ​
         return cnt;
     }
 ​
     int dx[2] = {0, 1};
     int dy[2] = {1, 0};
 ​
     void dfs(vector<vector<char>>& b, int i, int j) {
         b[i][j] = 'Y';
         for (int d = 0; d < 2; d++) {
             int ii = i + dx[d];
             int jj = j + dy[d];
             
             if (ii < 0 || jj < 0 || ii >= m || jj >= n) continue;
             if (b[ii][jj] == 'Y' || b[ii][jj] == '.') continue;
             dfs(b, ii, jj);
         }
     }
 ​
 ​
 };
 ​
 链接:https://leetcode-cn.com/problems/battleships-in-a-board/solution/wei-rao-li-lun-dfsjie-jue-lian-tong-tu-c-zu9v/

\