My JAVA DFS Solution


  • 0
    W
    class Solution {
        
        private int importance;
        
        public int getImportance(List<Employee> employees, int id) {
            int i, n = employees.size();
            boolean[] visited = new boolean[n];
            importance = 0;
            for(i = 0; i < n; i ++) visited[i] = false;
            dfs(id, employees, visited);
            return importance;
        }
        
        public void dfs(int id, List<Employee> employees, boolean[] visited) {
            if(visited[id - 1] == false) {
                visited[id - 1] = true;
                importance += employees.get(id - 1).importance;
                List<Integer> sub = employees.get(id - 1).subordinates;
                for(int j = 0; j < sub.size(); j ++) {
                    dfs(sub.get(j), employees, visited);
                }
                return;
            }
            else return;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.