您的位置:首页 > 其它

Battleships in a Board

2016-11-21 09:51 357 查看
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.
最近有点炸,感觉做动规的题一直没什么思路。觉得是时候整理一套动规的题了。

这道题之前看过的,当时没思路,现在看来跟number of island 应该是一个套路。可以用DFS来解。提示的O(n)的解法目前还没思路。用DFS的解法其实很直观,遍历整个数组,如果当前位置是X, 那么就DFS把它连着的X都设置成 * , 这样在统计X的次数的时候不会重复统计。

代码:

public int countBattleships(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == 'X') {
count++;
dfs(board, i, j);
}
}
}
return count;
}

private void dfs(char [][] board, int i, int j){
if(board[i][j] =='X'){
board[i][j] = '*';
if(i>0){
dfs(board, i-1, j);
}
if(i<board.length-1){
dfs(board, i+1, j);
}
if(j>0){
dfs(board, i, j-1);
}
if(j<board[0].length-1){
dfs(board, i, j+1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: