일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 코딩테스트
- github
- testcode
- jwt
- 회고록
- 알고리즘
- codingtest
- 자료구조
- Django
- kafkaconsumer
- 문자열함수
- AWS
- 시스템프로그래밍
- SpringSecurity
- 문자열압축
- 협업도구
- git
- 공부기록
- IT
- 자바
- 선택정렬
- 코테
- kafka
- java
- 기술블로그
- 기록
- c
- 한이음
- 트러블슈팅
- 백준
Archives
- Today
- Total
신뇽이 되어보자
[프로그래머스] 전력망을 둘로 나누기 (양방향 그래프, dfs) 본문
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/86971
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
import java.util.*;
class Solution {
//생각을 하자 생각
//일단 그래프 만들어(무방향 soooooooooooooooooooooo 양방향)
//1. 하나씩 다 끊어보기
//2. dfs + 백트래킹(백트래킹 까지는 아니네 .... 그냥 백트래킹 흉내 문제)
//3. 두 전력망이 가지고 있는 송전탑의 개수의 차이(절대값)들 중 최소 찾기(Math.min())
public ArrayList<Integer>[] graph;
public int answer;
public int solution(int n, int[][] wires) {
answer = Integer.MAX_VALUE;
graph = new ArrayList[n+1];
for(int i=1 ; i <= n; i++){
graph[i] = new ArrayList<>();
}
for (int i = 0; i < wires.length; i++) {
int v1 = wires[i][0];
int v2 = wires[i][1];
graph[v1].add(v2);
graph[v2].add(v1);
}
for(int i=0; i<wires.length; i++){
int n1 = wires[i][0];
int n2 = wires[i][1];
graph[n1].remove(Integer.valueOf(n2));
graph[n2].remove(Integer.valueOf(n1));
boolean[] visited = new boolean[n+1];
int cnt = dfs(n1, visited);
int diff = cnt - (n - cnt);
if(diff < 0){ //음수일 수도 있으니까
diff = diff * (-1);
}
answer = Math.min(answer,diff);
//다시 간선 추가
graph[n1].add(n2);
graph[n2].add(n1);
}
return answer;
}
public int dfs(int v, boolean[] visited){
visited[v] = true;
int cnt =1;
for(int next: graph[v]){
if(!visited[next]){
cnt+=dfs(next, visited);
}
}
return cnt;
}
}
728x90
'CodingTest' 카테고리의 다른 글
[프로그래머스] 배열 조작하기(Arrays.copyOfRange) (1) | 2025.02.24 |
---|---|
[프로그래머스] 소수 찾기 (dfs) (0) | 2025.02.24 |
[프로그래머스] 카펫 (완탐) (0) | 2025.02.22 |
[프로그래머스] 피로도 자바 (백트래킹, dfs) (1) | 2025.02.22 |
[조합] BOJ_15664 N과M(10)JAVA (1) | 2025.02.07 |