Skip to content

Commit f3eb2fc

Browse files
authored
Create Battleships in a Board.py
1 parent 994008a commit f3eb2fc

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Battleships in a Board.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
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:
3+
You receive a valid board, made of only battleships or empty slots.
4+
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.
5+
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
6+
Example:
7+
X..X
8+
...X
9+
...X
10+
In the above board there are 2 battleships.
11+
Invalid Example:
12+
...X
13+
XXXX
14+
...X
15+
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
16+
Follow up:
17+
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
18+
'''
19+
20+
class Solution(object):
21+
def countBattleships(self, board):
22+
"""
23+
:type board: List[List[str]]
24+
:rtype: int
25+
"""
26+
res = 0
27+
for i in xrange(len(board)):
28+
for j in xrange(len(board[i])):
29+
if board[i][j] == 'X':
30+
res += 1
31+
self.find(board, i, j)
32+
33+
return res
34+
35+
def find(self, board, x, y):
36+
vec = [(x, y)]
37+
board[x][y] = '.'
38+
39+
while vec:
40+
x, y = vec.pop()
41+
for i, j in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
42+
if 0 <= x + i < len(board) and 0 <= y + j < len(board[x+i]):
43+
if board[x+i][y+j] == 'X':
44+
vec.append((x+i, y+j))
45+
board[x+i][y+j] = '.'
46+

0 commit comments

Comments
 (0)