9월 5주차 [BFS/DFS]

justdoitjun·2023년 9월 29일

[BFS-DFS] Algorithm

목록 보기
3/9

[풀이실패] LeetCode 200 Number of Islands

풀이에 실패했다.
왜 나는 풀이에 실패했는가?
DFS 문제라는 것은 알겠다...! 하지만, 도대체 섬이라는 것을 어떻게 정의해야할지를 모르겠더라...

https://medium.com/@eric.christopher.ness/leetcode-200-number-of-islands-4dcd3ff971bb

# 난관 : 경우의 수니깐 DFS라는 건 알겠어. 근데, 도대체 '섬'을 어떻게 정의하지? 
# 여기선 4면이 바다('0')으로 surrounded된 경우를 섬이라고 하라고 하는데 말야. 
# 
from typing import List


class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        """Find number of islands in grid.
        Args:
            grid (List[List[str]]): Grid with 0s and 1s
        Returns:
            int: Number of islands
        """
        current_island = 2

        for row in range(len(grid)):
            for col in range(len(grid[0])):
                if grid[row][col] == "1":
                    mark_island(grid, row, col, str(current_island))
                    current_island += 1
        return current_island - 2


def mark_island(grid: List[List[str]], row: int, col: int, island_number: str):
    """Recursively mark all parts of an island with island_number.
    Args:
        grid (List[List[str]]): Grid with 0s and 1s
        row (int): Grid row
        col (int): Grid column
        island_number (str): Number to mark the island with
    """
    if row < 0 or col < 0 or row >= len(grid) or col >= len(grid[0]):
        return
    elif grid[row][col] == "0":
        return
    elif grid[row][col] == "1":
        grid[row][col] = island_number
        mark_island(grid, row - 1, col, island_number)
        mark_island(grid, row, col - 1, island_number)
        mark_island(grid, row + 1, col, island_number)
        mark_island(grid, row, col + 1, island_number)
        return
    else:
        return

[풀이성공] 프로그래머스 - 삼총사

class Solution {
//(아이디어)
//컴퓨터 방식대로라면, 하나씩 검증하는 게 가장 좋을 듯
// 배열 2개를 더해서, 이에 대응되는 숫자가 있는지 검증
// 그런데 이를 하나씩 다 검증하면 너무 어렵기 때문에..
// 대응되어야할 수보다 작으면 바로 break하거나 돌아가는 방법을 사용하여
// 런타임 줄일 수 있을 듯.
// (방법)
    public int solution(int[] number) {
        int answer = 0;
        for(int i=0; i< number.length ;i++){
            for(int j=i+1; j<number.length ; j++){
                int sumTest = 0; //초기화
                sumTest = number[i] + number[j];
                for(int p = j+1 ; p< number.length ;p++){
                    if(sumTest == number[p]*(-1)){
                        answer++;
                    }
                }
            }
        }
        return answer;
    }
}

[풀이성공] 프로그래머스 - 문자열 내 p와 y의 개수

class Solution {
 boolean solution(String s) {
     boolean answer;
     int numP = 0;
     int numY = 0;
     s = s.toLowerCase();
     for(int i = 0; i<s.length(); i++){
         String[] arr = new String[s.length()];
         arr = s.split("");
         if(arr[i].equals("p")){
             numP++;
         }else if(arr[i].equals("y")){
             numY++;
         }
     }
     if(numP == numY){
         answer = true;
     }else {
         answer = false;
     }
     return answer;
 }
}
profile
justdoitjun

0개의 댓글