반응형
난이도 - Medium
Intuition
DFS로 풀 수 있는 문제이다. 또한 Top-Left X cell만 구하는 식으로도 풀 수 있다.
Code
# DFS
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
ans = 0
rows = len(board)
cols = len(board[0])
for row in range(rows):
for col in range(cols):
if board[row][col] == "X":
ans += 1
board[row][col] = "O"
queue = []
queue.append((row, col))
while queue:
r, c = queue.pop()
# Vertical spaceship
if (r > 0 and board[r-1][c] == "X") or (r < rows-1 and board[r+1][c] == "X"):
if r > 0 and board[r-1][c] == "X":
queue.append((r-1, c))
board[r-1][c] = "O"
if r < rows-1 and board[r+1][c] == "X":
queue.append((r+1, c))
board[r+1][c] = "O"
# Horizontal spaceship
elif (c > 0 and board[r][c-1] == "X") or (c < cols-1 and board[r][c+1] == "X"):
if c > 0 and board[r][c-1] == "X":
queue.append((r, c-1))
board[r-1][c] = "O"
if c < cols-1 and board[r][c+1] == "X":
queue.append((r, c+1))
board[r][c+1] = "O"
return ans
# Top-Left cell counts
class Solution(object):
def countBattleships(self, board):
return sum(
board[i][j] == 'X' and
(i == 0 or board[i - 1][j] == '.') and
(j == 0 or board[i][j - 1] == '.')
for i in range(len(board))
for j in range(len(board[0]))
)
Complexity
Time Complexity: O(m*n)
Space Complexity: O(1)
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| 1060. Missing Element in Sorted Array (Array, Binary Search) (0) | 2025.10.23 |
|---|---|
| 3005. Count Elements With Maximum Frequency (Array, Hash Table, Counting) (0) | 2025.10.23 |
| 875. Koko Eating Bananas (Array, Binary Search) (0) | 2025.10.23 |
| 78. Subsets (Array, Backtracking, Bit Manipulation) (0) | 2025.10.23 |
| 4. Median of Two Sorted Arrays (Array, Binary Search, Divide and Conquer) (0) | 2025.10.23 |