Problem Solving with Algorithms

반응형

[Leetcode] 419. Battleships in a Board

 

leetcode.com/problems/battleships-in-a-board/

 

Battleships in a Board - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

요렇게 생각할 수 있겠으나

class Solution {
    public int countBattleships(char[][] board) {
        int res = 0, m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'X') {
                    res++;
                    helper(board, i, j);
                }
            }
        }
        
        return res;
    }
    
    public void helper(char[][] board, int i, int j) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != 'X')
            return;
        board[i][j] = '.';
        helper(board, i, j - 1);
        helper(board, i + 1, j);
        helper(board, i, j + 1);
        helper(board, i - 1, j);
    }
    
}

 

 

 

 

 

 

 

요고

class Solution {
    public int countBattleships(char[][] board) {
        int r = board.length;
        if(r == 0) return 0;
        int c = board[0].length;
        int count = 0;
        
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                if(board[i][j] == '.') continue;
                if(i > 0 && board[i-1][j] == 'X') continue;
                if(j > 0 && board[i][j-1] == 'X') continue;
                count++;
            }
        }
        return count;
    }
}

 

 

 

 

 

www.youtube.com/watch?v=zSQIGzmcp2I

 

 

 

youtu.be/wBG6078g1gE

 

반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band