본문 바로가기
[알고리즘 + 자료구조]/[프로그래머스]

프로그래머스 무인도 여행

by Hevton 2023. 7. 31.
반응형

 

 

익숙했던 느낌이라 굉장히 단시간에 해결해낼 수 있었다.

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool VISIT[100][100];

int AREA = 0;

int mx[4] = {0, 0, -1, 1};
int my[4] = {1, -1 ,0, 0};

int row, col;

void dfs(vector<string>& maps, int x, int y) {
    
    AREA += maps[x][y] - '0';
    VISIT[x][y] = true;
    
    for(int i = 0; i < 4; i++) {
        
        int xx = x + mx[i];
        int yy = y + my[i];
        
        if(xx < 0 || xx >= row || yy < 0 || yy >= col)
            continue;
        
        if(maps[xx][yy] != 'X' && !VISIT[xx][yy]) {
            dfs(maps, xx, yy);
        }
    }
    
}

vector<int> solution(vector<string> maps) {
    vector<int> answer;
    
    row = maps.size();
    col = maps[0].size();
    
    for(int i = 0; i < row; i++) {
        for(int j = 0; j < col; j++) {
            
            if(maps[i][j] != 'X' && !VISIT[i][j]) {
                
                AREA = 0;
                dfs(maps, i, j);
                answer.push_back(AREA);
            }
            
        }
    }
    
    
    sort(answer.begin(), answer.end(), less<int>());
    
    if(answer.size() == 0)
        answer.push_back(-1);
    
    return answer;
}

 

국경문제처럼 해결하면 된다.

반응형