본문 바로가기
  • 하루 끝에서
카테고리 없음

코딩테스트 연습 (무인도 여행, java)

by Eevy 2023. 8. 24.

프로그래머스 코딩테스트 연습문제 (무인도 여행)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.lang.Integer;
import java.lang.Boolean;


class Dfs{
    char[][] land = {};
    boolean[][] check = {};
    int sum = 0;
    ArrayList<Integer> fa = new ArrayList<>();
    Stack<Integer> sta = new Stack<>();

    void setDfs(char[][] a, int i, int j){
        land = new char[i][j];
        check = new boolean[i][j];
        for(int k=0; k<i; k++){
            Arrays.fill(check[k],false);
        }
        land = a;
    }

    void loop(int i, int j){
        if(i<0||i>=land.length) return;
        else if(j<0 || j>=land[0].length) return;
        else if(check[i][j]) return;
        check[i][j]=true;
        if(land[i][j]!='X'){
            sta.add(Character.getNumericValue(land[i][j]));
            loop(i,j+1);
            loop(i+1,j);
            loop(i,j-1);
            loop(i-1,j);
            sum +=sta.pop();
            if(sta.empty()){
            fa.add(sum);
            sum=0;
            }
        }
        if(sta.empty()) {
            for (int p = 0; p < land.length; p++) {
                for (int q = 0; q < land[0].length; q++) {
                    if (!check[p][q]) loop(p, q);
                }
            }
        }
    }
       int[] getResult(){
        if(fa.isEmpty()){
            int[] no = {-1};
            return no;
        }
        int[] ans = fa.stream().mapToInt(i->i).toArray();

        Arrays.sort(ans);
        return ans;
    }
}


class Solution {
    public int[] solution(String[] maps) {

        int mp = maps.length;
        int mp_s = maps[0].length();

        char[][] island = new char[mp][mp_s];
        for(int i = 0; i<mp; i++){
            island[i] = maps[i].toCharArray();
        }

        Dfs df = new Dfs();
        df.setDfs(island,mp,mp_s);
        df.loop(0,0);

        int[] answer = df.getResult();
        return answer;
    }
}

댓글


Top