| 19 | } |
| 20 | |
| 21 | public class Sanghoo { |
| 22 | |
| 23 | // BFS 어렵습니당.. 자꾸 보니까 조금 감이 잡히는것도 하네요 |
| 24 | public static int getImportance(List<Employee> employees, int id) { |
| 25 | int res = 0; |
| 26 | Queue<Employee> queue = new ArrayDeque(); |
| 27 | HashMap<Integer, Employee> hs = new HashMap(); |
| 28 | |
| 29 | // employees List를 돌며 root 노드를 찾아 큐에 삽입합니다. |
| 30 | // 위에 선언한 맵에 모든 employee들을 넣어주는 작업도 진행하는데, 고유 아이디로 쉽게 추출하기위해 추가하였습니다. |
| 31 | // 맵은 처음에 계속 반복문으로 찾으려다보니 너무 효율이 안좋아서 선택했습니다. |
| 32 | for(Employee em : employees) { |
| 33 | hs.put(em.id, em); |
| 34 | |
| 35 | if(em.id == id) { |
| 36 | queue.offer(em); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // 지난번 기초 BFS 문제인 Maximum Depth of Binary Tree 의 코드를 보고 작성해보았습니다. |
| 41 | // 기본적인 bfs 흐름은 같다고 생각합니다. |
| 42 | while(!queue.isEmpty()) { |
| 43 | |
| 44 | for(int i=0; i<queue.size(); i++) { |
| 45 | Employee em = queue.poll(); // 노드를 꺼내서 |
| 46 | |
| 47 | for(int sub : em.subordinates) { |
| 48 | queue.offer(hs.get(sub)); |
| 49 | } |
| 50 | |
| 51 | // 현재 노드의 importance를 더해줍니다. |
| 52 | res += em.importance; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | return res; |
| 57 | } |
| 58 | |
| 59 | public static void main(String[] args) { |
| 60 | List<Integer> a = new ArrayList(2); |
| 61 | a.add(2); |
| 62 | a.add(3); |
| 63 | |
| 64 | Employee em1 = new Employee(1,5, a); |
| 65 | Employee em2 = new Employee(2,3, new ArrayList<>()); |
| 66 | Employee em3 = new Employee(3,3, new ArrayList<>()); |
| 67 | List<Employee> employees = new ArrayList<Employee>(); |
| 68 | employees.add(em1); |
| 69 | employees.add(em2); |
| 70 | employees.add(em3); |
| 71 | |
| 72 | System.out.println(getImportance(employees, 1)); |
| 73 | } |
| 74 | } |
nothing calls this directly
no outgoing calls
no test coverage detected