출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
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님의 코드가 더 효율적으로 보인다.
하지만, 직관적인 측면에서 내 코드가 이해하기는 조금 더 쉽다고 생각하긴한다. 물론, 내가 짠 코드이기에 더더욱 그럴 것이다.
갑자기 어떤 코드가 더 효율적인 것인가 의문에 빠지게 되었다....
메모리는 덜 잡아먹지만 이해하기 힘든 코드와 메모리를 더 잡아먹고 이해하기 편한 코드라면 어떤 코드가 더 좋은 코드인가 고민하게 되었다.
오픈톡방에 사람들은 후자의 코드가 훨씬 좋은 코드라 말한다.
과연 뭐가 좋은 코드일까 좀 더 고민해봐야겠다.
백준 3055 탈출(bfs) (0) | 2020.08.14 |
---|---|
백준 14891 톱니바퀴(구현, 시뮬레이션) (0) | 2020.08.13 |
백준 2250 트리의 높이와 너비(dfs, inorder traversal) (0) | 2020.08.06 |
백준 7562 나이트의 이동(bfs) (0) | 2020.08.05 |
백준 1613 역사(floyd-warshall) (0) | 2020.08.04 |
댓글 영역