본문 바로가기
Coding Test/Programmers

[Programmers] Lv 2. 무인도 여행

by song.ift 2023. 8. 5.

https://school.programmers.co.kr/learn/courses/30/lessons/154540

 

프로그래머스

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

programmers.co.kr

 

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

using namespace std;

int dfs(int x, int y, vector<vector<bool>>& visited, const vector<pair<int, int>>& dir, const vector<string>& maps)
{
    int value = maps[x][y] - '0';
    visited[x][y] = true;

    for (const auto& d : dir)
    {
        int tx = x + d.first,
            ty = y + d.second;

        if (tx < 0 || tx >= maps.size() || ty < 0 || ty >= maps[0].length()) continue;
        if (maps[tx][ty] == 'X' || visited[tx][ty]) continue;

        value += dfs(tx, ty, visited, dir, maps);
    }
    return value;
}

vector<int> solution(vector<string> maps) {
    vector<int> answer;
    size_t row = maps.size(), col = maps[0].length();
    vector<vector<bool>> visited(row, vector<bool>(col, false));
    const vector<pair<int, int>> dir = { {0, -1}, {0, 1}, {1, 0}, {-1, 0} };
    
    for (size_t x = 0; x < row; ++x)
    {
        for (size_t y = 0; y < col; ++y)
        {
            if (maps[x][y] == 'X' || visited[x][y]) continue;

            answer.emplace_back(dfs(x, y, visited, dir, maps));
        }
    }

    if (answer.empty()) answer.emplace_back(-1);
    else ::stable_sort(answer.begin(), answer.end());

    return answer;
}

GitHub : https://github.com/developeSHG/Algorithm-Baekjoon_Programmers/commit/4f4a1d19855c5208edeaca83339f528f74c254b1

 

[unrated] Title: 무인도 여행, Time: 0.03 ms, Memory: 4.2 MB -BaekjoonHub · developeSHG/Algorithm-Baekjoon_Programmers@4f4a

developeSHG committed Aug 5, 2023

github.com

 

댓글