Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Battleships in a Board(Array,Depth-First Search,Matrix)

eatplaylove 2024. 11. 21. 21:31

https://leetcode.com/problems/battleships-in-a-board/description/

Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.

Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).

 

Example 1:

Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2

Example 2:

Input: board = [["."]]
Output: 0

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is either '.' or 'X'.

 

Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?


 

 

아 진짜 왜 코딩으로 계속 게임을 만드는 것인가.. 짜증이 난다 짜증이 나!!

 

일단 Python으로 간 좀 보기

 

1. Python

그간 풀던 문제들이랑 결이 좀 비슷해서 어찌어찌 풀긴했다.

역시나 Naive하긴 하다 ㅎㅎ;;

class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
        visited = []
        direction = [[0,1],[0,-1],[-1,0],[1,0],[0,0]]
        m = len(board)
        n = len(board[0])
        # find X and make all the neighbors of it visited
        def helper(i:int,j:int) -> None :
            for dx,dy in direction:
                new_i = i+dx
                new_j = j+dy
                if 0<=new_i<m and 0<=new_j<n and board[new_i][new_j] == "X" and (new_i,new_j) not in visited:
                    visited.append((new_i,new_j))
                    helper(new_i,new_j)
        cnt = 0
        for i in range(m):
            for j in range(n):
                if board[i][j] == "X" and (i,j) not in visited:
                    cnt+=1
                    helper(i,j)
        return cnt

거진 꼴지 ㄷㄷ;

 

이것을 좀 더 간단하게 푼 것을 C++로 나타내어 보자

 

2. C++

using namespace std;
#include <vector>

class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        int ans = 0;
        int m = board.size();
        int n = board[0].size();

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(board[i][j]=='X'){
                    if((i==0 || board[i-1][j] =='.') && (j==0 || board[i][j-1]=='.')) ans++;
                    // 위 or 왼쪽이 없거나 '.'이면 전함 cnt증가
                }
            }
        }
        return ans;
    }
};

 

롤리 포올리~~