forked from 2021-Algorithm/algorithms_site
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
programmers/level2/DividingPowerGringIntoTwo
- Loading branch information
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package level2; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
// https://programmers.co.kr/learn/courses/30/lessons/86971?language=java | ||
public class DividingPowerGridIntoTwo { | ||
public static void main(String[] args) { | ||
DividingPowerGridIntoTwo e = new DividingPowerGridIntoTwo(); | ||
System.out.println(e.solution(4, new int[][]{{1,2},{2,3},{3,4}})); | ||
|
||
} | ||
public int search(List<List<Integer>> graph, int n1, int n2) { | ||
int cnt = 0; | ||
System.out.println(graph); | ||
System.out.println("n1 = " + n1); | ||
for(int des : graph.get(n1)) { | ||
if(des==n2) { | ||
continue; | ||
} | ||
else { | ||
cnt++; | ||
cnt += search(graph, des, n1); | ||
} | ||
} | ||
return cnt; | ||
} | ||
|
||
public int solution(int n, int[][] wires) { | ||
List<List<Integer>> graph = new ArrayList<>(); | ||
for(int i=0; i<n+1; i++) { | ||
graph.add(new ArrayList<>()); | ||
} | ||
|
||
for(int[] wire:wires) { | ||
int n1 = wire[0]; | ||
int n2 = wire[1]; | ||
graph.get(n1).add(n2); | ||
graph.get(n2).add(n1); | ||
} | ||
|
||
int answer = 200; | ||
for(int[] wire : wires) { | ||
answer = Math.min(answer, Math.abs(search(graph, wire[0], wire[1]) - search(graph, wire[1], wire[0]))); | ||
} | ||
return answer; | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
## https://programmers.co.kr/learn/courses/30/lessons/86971?language=java | ||
def real_search(graph, i, caller): | ||
cnt = 0 | ||
for des in graph[i]: | ||
if des != caller: | ||
cnt += 1 | ||
cnt += real_search(graph, des, i) | ||
return cnt | ||
|
||
def search(graph, i, j): | ||
return abs(real_search(graph, i, j) - real_search(graph, j, i)) | ||
|
||
def solution(n, wires): | ||
graph = [[] for _ in range(n+1)] | ||
for node1, node2 in wires: | ||
graph[node1].append(node2) | ||
graph[node2].append(node1) | ||
|
||
answer = 200 | ||
for node1, node in wires: | ||
answer = min(answer, search(graph, node1, node)) | ||
|
||
return answer | ||
|