728x90
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import java.util.*; class Solution { private static List<Node> nodeList; private static boolean[][] visited; public int solution(int n, int[][] wires) { int answer = Integer.MAX_VALUE; nodeList = new ArrayList<>(); for(int i=0; i<=n; i++){ nodeList.add(new Node(i)); } for(int[] wire : wires){ int a = wire[0]; int b = wire[1]; nodeList.get(a).edgeList.add(b); nodeList.get(b).edgeList.add(a); } for(int[] wire : wires){ int a = wire[0]; int b = wire[1]; nodeList.get(a).edgeList.remove(new Integer(b)); nodeList.get(a).edgeList.remove(new Integer(a)); visited = new boolean[n+1][n+1]; int nodeCandiNum = BFS(a); // System.out.println(nodeCandiNum); answer = Math.min(answer, Math.abs(2*nodeCandiNum-n)); nodeList.get(a).edgeList.add(b); nodeList.get(b).edgeList.add(a); } return answer; } private class Node{ int num; List<Integer> edgeList; public Node(int num){ this.num = num; edgeList = new ArrayList<>(); } } private int BFS(int num){ int ret = 0; Queue<Node> q = new LinkedList<>(); q.offer(nodeList.get(num)); while(!q.isEmpty()){ Node node = q.poll(); int currNum = node.num; List<Integer> edgeList = node.edgeList; ret++; // System.out.print(currNum+" "); for(int i=0; i<edgeList.size(); i++){ int nodeNum = edgeList.get(i); if(!visited[currNum][nodeNum]){ q.offer(nodeList.get(nodeNum)); visited[currNum][nodeNum] = true; visited[nodeNum][currNum] = true; } } } return ret; } } | cs |
'알고리즘 풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스][JAVA] 옹알이 (String) (0) | 2022.10.31 |
---|---|
[프로그래머스][JAVA] 교점에 별 만들기 (구현) (0) | 2022.04.11 |
[프로그래머스][JAVA] 구명보트 (그리디) (0) | 2022.04.03 |
[프로그래머스][JAVA] 주식가격 (완전탐색) (0) | 2022.04.03 |
[프로그래머스][JAVA] 영어 끝말잇기 (HashSet) (0) | 2022.04.03 |