Guest User

Untitled

a guest
Apr 21st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.23 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. import java.util.Scanner;
  4.  
  5. class Pair {
  6. int x;
  7. int y;
  8. Pair(int x, int y) {
  9. this.x = x;
  10. this.y = y;
  11. }
  12. }
  13.  
  14. public class Main {
  15. public static final int[] dx = {0,0,1,-1};
  16. public static final int[] dy = {1,-1,0,0};
  17. public static int[][] inputAry;
  18. public static int[][] group;
  19. public static int[][] dist;
  20. public static void main(String[] args) {
  21. Scanner sc = new Scanner(System.in);
  22. int n = sc.nextInt();
  23.  
  24. inputAry = new int[n][n];
  25. //섬의 번호가 매겨져 저장된 2차원 배열
  26. group = new int[n][n];
  27.  
  28. for(int i = 0; i < n; i++) {
  29. for(int j = 0; j < n; j++) {
  30. inputAry[i][j] = sc.nextInt();
  31. }
  32. }
  33. int cnt = 0;
  34. for(int i = 0; i < n; i++) {
  35. for(int j = 0; j < n; j++) {
  36. if(inputAry[i][j] == 1 && group[i][j] == 0) {
  37. dfs(i,j,n,++cnt);
  38. }
  39. }
  40. }
  41. int answer = Integer.MAX_VALUE;
  42. for(int i = 1; i <= cnt; i++) {
  43. answer = Math.min(answer, bfs(i, n));
  44. }
  45. System.out.println(answer);
  46. }
  47. public static void dfs(int x, int y, int n, int cnt) {
  48. group[x][y] = cnt;
  49. for(int i = 0; i < 4; i++) {
  50. int nx = x + dx[i];
  51. int ny = y + dy[i];
  52. if(nx >= 0 && ny >= 0 && nx < n && ny < n) {
  53. if(inputAry[nx][ny] == 1 && group[nx][ny] == 0) {
  54. dfs(nx,ny,n,cnt);
  55. }
  56. }
  57. }
  58. }
  59. // 반환값 : 섬 번호가 cnt일 때, 나머지 섬들에 다리를 놓을 때 최단 거리
  60. public static int bfs(int cnt, int n) {
  61. Queue<Pair> q = new LinkedList<Pair>();
  62. dist = new int[n][n];
  63. for(int i = 0; i < n; i++) {
  64. for(int j = 0; j < n; j++) {
  65. //현재 섬의 번호가 cnt일 때는 거리에 0을 넣어주고, 다른 섬일 때는 -2, 그리고 바다 일때는 -1
  66. if(group[i][j] == cnt) {
  67. dist[i][j] = 0;
  68. q.add(new Pair(i,j));
  69. } else if (group[i][j] == 0) {
  70. dist[i][j] = -1;
  71. } else {
  72. dist[i][j] = -2;
  73. }
  74. }
  75. }
  76.  
  77. int min = Integer.MAX_VALUE;
  78.  
  79. while(!q.isEmpty()) {
  80. Pair p = q.remove();
  81. int x = p.x;
  82. int y = p.y;
  83. for(int i = 0; i < 4; i++) {
  84. int nx = x + dx[i];
  85. int ny = y + dy[i];
  86. if(nx >= 0 && ny >= 0 && nx < n && ny < n) {
  87. // cnt번의 섬에서 다른 섬에 접근되었을 때 타게 되는 분기
  88. // dist[x][y]에 최단거리가 담기므로 이전 다리길이와 비교해 최소값을 갱신해준다
  89. if(dist[nx][ny] == -2) {
  90. min = Math.min(min, dist[x][y]);
  91. continue;
  92. } else if(dist[nx][ny] == -1) {
  93. q.add(new Pair(nx,ny));
  94. dist[nx][ny] = dist[x][y] + 1;
  95. }
  96. }
  97. }
  98. }
  99. return min;
  100. }
  101. }
Add Comment
Please, Sign In to add comment