본문 바로가기
#알고리즘 [Algorithm]/Problem

[프로그래머스 - 그래프] 가장 먼 노드

by cy_mos 2019. 4. 5.
반응형
카테고리 게시글 작성 날짜 게시글 최근 수정 날짜 작성자
Algorithm 2019-04-05 22:00 2022.02.25. 01:23 Dev.Yang

 

n개의 노드가 있는 그래프가 있습니다. 각 노드는 1부터 n까지 번호가 적혀있습니다. 1번 노드에서 가장 멀리 떨어진 노드의 갯수를 구하려고 합니다. 가장 멀리 떨어진 노드란 최단경로로 이동했을 때 간선의 개수가 가장 많은 노드들을 의미합니다.

 

노드의 개수 n, 간선에 대한 정보가 담긴 2차원 배열 vertex가 매개변수로 주어질 때, 1번 노드로부터 가장 멀리 떨어진 노드가 몇 개인지를 return 하도록 solution 함수를 작성해주세요.

 

[제한사항]

  • 노드의 개수 n은 2 이상 20,000 이하입니다.
  • 간선은 양방향이며 총 1개 이상 50,000개 이하의 간선이 있습니다.
  • vertex 배열 각 행 [a, b]는 a번 노드와 b번 노드 사이에 간선이 있다는 의미입니다.

📄 [그래프] 가장 먼 노드 with C++ Source Code

더보기
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;

#define ZERO 0

typedef vector<int> NodeMap;
typedef vector<bool> VisitMap;

int findAwayNode(vector<NodeMap> nodeMap, vector<bool> & isVisit, const int index, const int length) {
    
    int answer = ZERO;
    int awayMaxValue = ZERO;
    
    vector<int> dist = vector<int>(length, ZERO);
   
    queue<int> bucket = queue<int>();
    bucket.push(index);
    
    dist[index] = 1;
    isVisit[index] = true;
    
    while(bucket.empty() == false) {
        
        const auto value = bucket.front();
        bucket.pop();
        
        for (const auto node : nodeMap[value]) {
            if (isVisit[node]) { continue; }
            
            dist[node] = dist[value] + 1;
            awayMaxValue = std::max(dist[node], awayMaxValue);
            
            bucket.push(node);
            isVisit[node] = true;
        }
    };
    
    // 주어진 노드에서 가장 멀리 떠어진 노드의 간선의 수에 해당하는 노드를 찾습니다.
    for (const int value : dist) {
        if (value == awayMaxValue) { answer++; }
    }
    
    return answer;
}

int solution(int n, vector<vector<int>> edge) {
    
    vector<NodeMap> map = vector<NodeMap>(n, NodeMap());
    
    // 주어진 간선을 통하여 무방향의 그래프를 생성합니다.
    for (const auto pos : edge) {
        const auto first = pos.front();
        const auto second = pos.back();
        
        map[first - 1].push_back(second - 1);
        map[second - 1].push_back(first - 1);
    }
    
    VisitMap visit = VisitMap(n, false);
    int answer = findAwayNode(map, visit, ZERO, n);
    
    // NOTE: - 가장 멀리 떨어진 노드란 최단경로로 이동했을 때 간선의 개수가 가장 많은 노드를 구합니다.
    return answer;
}

📄 [그래프] 가장 먼 노드 with Swift Source Code

더보기
import Foundation

let CONNECTED: Int = 1
let UNCONNCTED: Int = 0

public struct Queue<T> {
    fileprivate var array = [T]()
    
    public var front: T? { return array.first }
    public var count: Int { return array.count }
    public var isEmpty: Bool { return array.isEmpty }
    public mutating func enqueue(_ element: T) { array.append(element) }
    public mutating func dequeue() -> T? { return isEmpty ? nil : array.removeFirst() }
}

func findShortDistance(size: Int, index: Int, visited: inout [Int], board: [[Int]]) {
    
    visited[index] = CONNECTED
    
    var queue = Queue<Int>()
    queue.enqueue(index)
    
    while !queue.isEmpty {
        
        guard let here = queue.front else { break }
        queue.dequeue()
        
        for index in board[here] where visited[index] < CONNECTED {
            queue.enqueue(index)
            visited[index] = visited[here] + 1
        }
     }
}


func solution(_ n:Int, _ edge:[[Int]]) -> Int {
    
    // MARK: - 인접행렬 (Adjacency Matrix)
    var board = [[Int]](repeating: Array<Int>(), count: n)
    var visited = Array<Int>(repeating: UNCONNCTED, count: n)
    
    for node in edge {
        let index: (first: Int, second: Int) = (node.first! - 1, node.last! - 1)
        // MARK: - U간선은 양방향이며 총 1개 이상 50,000개 이하의 간선이 있습니다. vertex 배열 각 행 [a, b]는 a번 노드와 b번 노드 사이에 간선이 있다는 의미입니다.
        board[index.first].append(index.second)
        board[index.second].append(index.first)
    }
    
    // MARK: - 1번 노드에서 가장 멀리 떨어진 노드의 갯수를 구하려고 합니다.
    findShortDistance(size: n, index: 0, visited: &visited, board: board)
    
    // MARK: - 1번 노드로부터 가장 멀리 떨어진 노드가 몇 개인지를 return 하도록 solution 함수를 작성해주세요.
    visited.sort()
    return visited.filter { visited.last! == $0 }.count
}

🚀 REFERENCE

반응형

댓글