Skip to content

Instantly share code, notes, and snippets.

@gowoonsori
Created November 9, 2021 01:43
Graph
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
void bfs(vector<bool> &visited,vector<vector<int>> edge,vector<int> &distance, int node){
queue<int> q;
q.push(node);
visited[0] = true;
visited[node] = true;
while(!q.empty()){
node = q.front();
q.pop();
for(int i=0; i < edge.size(); i++){
if(edge[i][0] == node && !visited[edge[i][1]]){
int n =edge[i][1];
distance[n] = distance[node] + 1;
q.push(n);
visited[n] = true;
}
else if(edge[i][1] == node && !visited[edge[i][0]]){
int n =edge[i][0];
distance[n] = distance[node] + 1;
q.push(n);
visited[n] = true;
}
}
}
}
int solution(int n, vector<vector<int>> edge) {
int answer = 0;
vector<bool> visited(n+1,false);
vector<int> distance(n+1, 0);
bfs(visited,edge,distance, 1);
sort(distance.begin(), distance.end(), greater<int>());
int max_dis = distance[0];
for(int d : distance) if(d == max_dis) answer++;
return answer;
}
#include <iostream>
#include <cstring>
using namespace std;
int graph[1001][1001];
int visited[1001];
int N,M,V;
void dfs(int v){
cout<< v << " ";
visited[v]=1;
for(int i=1; i<=N ;i++){
if(graph[v][i] && !visited[i])
dfs(i);
}
}
int main(){
int a,b;
memset(graph,0,sizeof(graph));
memset(visited,0,sizeof(visited));
cout <<"정점, 간선, 시작 정점 : ";
cin >> N >> M >> V;
for(int i=0; i<M; i++){
cout << "연결된 두 정점 번호 : ";
cin >> a >> b;
graph[a][b]=1;
graph[b][a]=1;
}
dfs(V);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment