题目
Given an 2D board, count how many 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.
答案
代码太长了,应该还有优化的空间
class Solution {
private boolean isVertShip(char[][] board, int x, int y) {
int topx = x - 1, topy = y;
int botx = x + 1, boty = y;
if(topx >= 0 && topx < board.length && topy >= 0 && topy < board[0].length && board[topx][topy] == 'X')
return true;
if(botx >= 0 && botx < board.length && boty >= 0 && boty < board[0].length && board[botx][boty] == 'X')
return true;
// no 'X' on top or bottom, must be a horizontal ship
return false;
}
private boolean isShipEnd(char[][] board, int x, int y) {
if(isVertShip(board, x, y)) {
int botx = x + 1, boty = y;
// if bottom is '.' or out of bounds, then this is the end of a ship
return (botx >= board.length || board[botx][boty] == '.');
}
else {
int rightx = x, righty = y + 1;
return (righty >= board[0].length || board[rightx][righty] == '.');
}
}
public int countBattleships(char[][] board) {
if(board.length == 0) return 0;
int ans = 0;
// go one pass
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j] == 'X') {
if(isShipEnd(board, i, j))
ans++;
}
}
}
return ans;
}
}