출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 2644 촌수계산(bfs)

알고리즘

by 장동균 2020. 8. 11. 23:12

본문

https://www.acmicpc.net/problem/2644

 

2644번: 촌수계산

사람들은 1, 2, 3, …, n (1≤n≤100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어진�

www.acmicpc.net

#include <iostream>
#include <vector>
#include <queue>

using namespace std;
const int MAX=100+1;

vector<int> graph[MAX];
bool visited[MAX];
int n;
int parent, child;
typedef struct {
    int x, y, count;
}point;

int bfs(int x, int count) {
    queue<point> q;
    for (int i=0;i<graph[x].size();i++) {
        q.push({ x, graph[x][i], count });
    }
    visited[x]=true;
    while (!q.empty()) {
        int nextX=q.front().x;
        int nextY=q.front().y;
        int nextCount=q.front().count;
        q.pop();
        if (nextY==child) {
            return nextCount;

        }
        if (!visited[nextY]) {
            for (int i=0;i<graph[nextY].size();i++) {
                if (!visited[graph[nextY][i]]) {
                    q.push({ nextY, graph[nextY][i], nextCount+1 });
                }
            }
            visited[nextY]=true;

        }
    }

    return -1;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    cin>>parent>>child;
    int edge;
    cin>>edge;
    for (int i=0;i<edge;i++) {
        int node1, node2;
        cin>>node1>>node2;
        graph[node1].push_back(node2);
        graph[node2].push_back(node1);
    }
    cout<<bfs(parent, 1);

}

https://jaimemin.tistory.com/search/2644

 

꾸준함

소소한 프로그래밍과 약간의 게임

jaimemin.tistory.com

jaimemin님의 코드와 사뭇다르다. 내가 보기에도 내 코드 보다는 jaimemin님의 코드가 더 효율적으로 보인다.

하지만, 직관적인 측면에서 내 코드가 이해하기는 조금 더 쉽다고 생각하긴한다. 물론, 내가 짠 코드이기에 더더욱 그럴 것이다.

 

갑자기 어떤 코드가 더 효율적인 것인가 의문에 빠지게 되었다....

 

메모리는 덜 잡아먹지만 이해하기 힘든 코드와 메모리를 더 잡아먹고 이해하기 편한 코드라면 어떤 코드가 더 좋은 코드인가 고민하게 되었다.

 

오픈톡방에 사람들은 후자의 코드가 훨씬 좋은 코드라 말한다. 

 

과연 뭐가 좋은 코드일까 좀 더 고민해봐야겠다.

관련글 더보기

댓글 영역