티스토리 뷰
각 노드에서 자신을 제외한 노드로 이동하는 최단거리를 구하여 모두 더하는 문제이다.
BFS를 이용하여 문제를 해결할 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sdk.algo.shortdist; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.Scanner; | |
/** | |
* 정올, 알고리즘, 최단거리, 1108 | |
* 페이지 전환 | |
* | |
* @author whitebeard-k | |
* | |
*/ | |
public class Problem1108 { | |
public static int bfs(Queue<Integer> queue, int[][] array, int[] visited, int target, int moveCount) { | |
int size = queue.size(); | |
while (size-- > 0) { | |
int loc = queue.poll(); | |
if (loc == target) | |
return moveCount; | |
else { | |
for (int i = 0; i < array.length; i++) { | |
if (loc != i && visited[i] != 1 && array[loc][i] == 1) { | |
visited[i] = 1; | |
queue.add(i); | |
} | |
} | |
} | |
} | |
return bfs(queue, array, visited, target, ++moveCount); | |
} | |
public static void main(String[] args) { | |
// int n = 5; | |
// int[][] inputs = {{ 1 ,2 }, | |
// { 2 ,4 }, | |
// { 1 ,3 }, | |
// { 3 ,1 }, | |
// { 4 ,3 }}; | |
// int max = 4; | |
int max = Integer.MIN_VALUE; | |
Scanner sc = new Scanner(System.in); | |
int n = sc.nextInt(); | |
int[][] inputs = new int[n][2]; | |
for (int i = 0; i < n; i++) { | |
inputs[i][0] = sc.nextInt(); | |
inputs[i][1] = sc.nextInt(); | |
max = (inputs[i][0] > max) ? inputs[i][0] : max; | |
max = (inputs[i][1] > max) ? inputs[i][1] : max; | |
} | |
sc.close(); | |
int[][] array = new int[max + 1][max + 1]; | |
for (int i = 0; i < n; i++) { | |
array[inputs[i][0]][inputs[i][1]] = 1; | |
} | |
Queue<Integer> queue = new LinkedList<>(); | |
float sum = 0; | |
float count = 0; | |
for (int start = 1; start < n; start++) { | |
for (int i = 1; i < n; i++) { | |
if (start == i) | |
continue; | |
queue.clear(); | |
queue.add(start); | |
int[] visited = new int[max+1]; | |
visited[start] = 1; | |
int result = bfs(queue, array, visited, i, 0); | |
sum += result; | |
count++; | |
} | |
} | |
System.out.printf("%.3f", sum / count); | |
} | |
} |
반응형
'알고리즘 > 정올' 카테고리의 다른 글
[정올][다이나믹] 1520 계단오르기 (0) | 2017.04.13 |
---|---|
[정올][다이나믹] 1407 숫자카드 (0) | 2017.04.13 |
[정올][다이나믹] 1848 극장좌석 (0) | 2017.04.11 |
[정올][백트래킹] 1027 좋은 수열 (0) | 2016.10.09 |
[정올][그리디] 2499 저울 (0) | 2016.10.07 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- nodejs
- Linux
- airflow
- java
- 알고리즘
- S3
- 다이나믹
- AWS
- mysql
- Tez
- SPARK
- Python
- 백준
- Hadoop
- HIVE
- error
- 오류
- emr
- SQL
- bash
- 정올
- 하이브
- 하둡
- build
- ubuntu
- oozie
- HDFS
- 파이썬
- hbase
- yarn
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함