본문 바로가기
백준 알고리즘/BFS

백준 1389번 C++

by paysmile 2019. 1. 13.

#include <iostream>

#include <cstring>

using namespace std;


const int MAX = 987654321;

const int arr = 100;

int n, m;

int graph[arr][arr];


void floyd() {


for (int k = 1; k <= n; k++) {

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

if (i == j)

continue;

else if (graph[i][k] != 0 && graph[k][j] != 0) {

if (graph[i][j] > graph[i][k] + graph[j][k]) {

graph[i][j] = graph[i][k] + graph[j][k];

}

}

}

}

}

}


int main(void) {

cin >> n >> m;


for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

if (i == j)

graph[i][j] = 0;

else

graph[i][j] = MAX;

}

}

for (int i = 0; i < m ; i++) {

int x, y;

cin >> x >> y;

graph[x][y] = 1;

graph[y][x] = 1;

}


floyd();


int ans;

int shortest = 987654321;

for (int i = 1; i <= n; i++) {

int counts = 0;

for (int j = 1; j <= n; j++) {

counts += graph[i][j];

}

if (counts < shortest) {

shortest = counts;

ans = i;

}

}

cout << ans;

}

'백준 알고리즘 > BFS' 카테고리의 다른 글

백준 2589번 C++  (0) 2019.01.14
백준 10026번 C++  (0) 2019.01.13
백준 2644번 C++  (0) 2019.01.12
백준 14502번 C++  (0) 2019.01.10
백준 2468번 C++  (0) 2019.01.09