leetcode oj java Battleships in a Board

胥和悌
2023-12-01

一、问题描述:

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:

...X
XXXX
...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

二、解决方案:

要求任意两个战舰之间不会近邻,那么只需要找到战舰的头元素就可以了。头元素必须保证 tmp[i][j] == 'X' && tmp[i - 1][j] == '.' && tmp[i][j - 1] == '.'  ,即本身为'X'但是左方和上方都为'.' 。 否则即为空的分割点或者是战舰的中间元素。我们新建一个tmp数组保存board,在最上边和最左边各加一列'.'。  满足one-pass的要求。

三、代码:

public class Solution {
    public int countBattleships(char[][] board) {
        int re = 0;
        int l = board.length;
        int w = board[0].length;
        char[][] tmp = new char[l + 1][w + 1];

        for (int i = 0; i < l; i++) {
            for (int j = 0; j < w; j++) {
                tmp[i + 1][j + 1] = board[i][j];
            }
        }

        for (int i = 0; i < w + 1; i++) {
            tmp[0][i] = '.';
        }
        for (int i = 0; i < l + 1; i++) {
            tmp[i][0] = '.';
        }

        for (int i = 1; i < l+1; i++) {
            for (int j = 1; j < w + 1; j++) {
                if (tmp[i][j] == 'X' && tmp[i - 1][j] == '.' && tmp[i][j - 1] == '.')
                    re++;
            }
        }
        return re;
    }
}


 类似资料:

相关阅读

相关文章

相关问答