본문 바로가기
개인 공부/TIL

[ TIL - PGS ] 99클럽 코테 스터디 32일차 TIL + 오늘의 학습 가이드

by 킴도비 2024. 8. 22.

💡 오늘의 학습 키워드

  • 깊이/너비 우선 탐색(DFS/BFS)

 

✅ 오늘 공부한 내용

  • 오늘의 프로그래머스 문제! 무인도 여행
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

👀 오늘의 회고

🤣 오늘의 문제점

  • 오늘은 시간이 없는 관계로 급하게 했다...

 

🔥 어떤 시도를 했는가?

  • 아래는 풀이 코드이다.
import java.util.*;

public class Solution {
    // 상, 하, 좌, 우로의 이동을 표현하기 위한 배열
    private static final int[] dx = {0, 0, -1, 1};
    private static final int[] dy = {-1, 1, 0, 0};

    public int[] solution(String[] maps) {
        int n = maps.length;
        int m = maps[0].length();
        
        boolean[][] visited = new boolean[n][m];
        List<Integer> results = new ArrayList<>();
        
        // 지도를 순회하면서 무인도를 찾음
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // 아직 방문하지 않았고, 'X'가 아닌 숫자가 있는 경우 새로운 무인도를 찾음
                if (!visited[i][j] && maps[i].charAt(j) != 'X') {
                    int days = dfs(maps, visited, i, j, n, m);
                    results.add(days);
                }
            }
        }
        
        // 결과를 정렬하여 반환
        if (results.isEmpty()) {
            return new int[]{-1};
        } else {
            Collections.sort(results);
            return results.stream().mapToInt(i -> i).toArray();
        }
    }

    // DFS를 사용해 무인도를 탐색하고, 해당 무인도에 있는 숫자의 합을 구함
    private int dfs(String[] maps, boolean[][] visited, int x, int y, int n, int m) {
        Stack<int[]> stack = new Stack<>();
        stack.push(new int[]{x, y});
        visited[x][y] = true;
        int sum = 0;

        while (!stack.isEmpty()) {
            int[] current = stack.pop();
            int cx = current[0];
            int cy = current[1];
            
            // 현재 위치의 숫자를 합산
            sum += maps[cx].charAt(cy) - '0';
            
            // 상하좌우로 연결된 땅들을 탐색
            for (int i = 0; i < 4; i++) {
                int nx = cx + dx[i];
                int ny = cy + dy[i];
                
                if (nx >= 0 && ny >= 0 && nx < n && ny < m && !visited[nx][ny] && maps[nx].charAt(ny) != 'X') {
                    visited[nx][ny] = true;
                    stack.push(new int[]{nx, ny});
                }
            }
        }
        
        return sum;
    }
}

 

👏 무엇을 새로 알았는가?

  • DFS 활용법

 

👩‍💻 내일은 무엇을 학습할 것인가?

  • 항해99문제 풀기
  • 책 읽기(제발)
  • 과제 하기