Skip to content

Commit

Permalink
programmers/level2/DividingPowerGringIntoTwo
Browse files Browse the repository at this point in the history
  • Loading branch information
bong6981 committed May 30, 2022
1 parent b399b12 commit 82decb5
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
48 changes: 48 additions & 0 deletions programmers/java/src/level2/DividingPowerGridIntoTwo.java
@@ -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;
}
}
24 changes: 24 additions & 0 deletions programmers/python/level2/divide_power_grid_into_two.py
@@ -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

0 comments on commit 82decb5

Please sign in to comment.