diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 0000000..d2dfdde --- /dev/null +++ b/Problem1.java @@ -0,0 +1,59 @@ +//o(mxn) time complexity +//o(mxn) space complexity +//bfs + + + +class Solution { + public int orangesRotting(int[][] grid) { + + Queue queue = new LinkedList<>(); + int m = grid.length; + int n = grid[0].length; + int freshOrangesCount = 0; + + for(int i = 0; i< m; i++){ + for (int j = 0; j < n ; j++){ + if(grid[i][j] == 2){ + queue.offer(new int[]{i,j}); + } + + if(grid[i][j] == 1) { + freshOrangesCount++; + } + } + } + + if(freshOrangesCount == 0){ + return 0; + } + + if(queue.size() == 0){ + return -1; + } + + int minutes = -1; + + int[][] dirs = {{1,0}, {-1,0},{0,-1},{0,1} }; + + while(!queue.isEmpty()){ + int size = queue.size(); + minutes++; + for(int k =0; k< size; k++){ + int[] curr = queue.poll(); + int r = curr[0]; + int c = curr[1]; + for(int[] dir: dirs){ + int nr = r + dir[0]; + int nc = c + dir[1]; + if(nr >= 0 && nr < m && nc >=0 && nc < n && grid[nr][nc] == 1){ + grid[nr][nc] = 2; + freshOrangesCount--; + queue.offer(new int[]{nr,nc}); + } + } + } + } + return freshOrangesCount == 0 ? minutes : -1; + } +} diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 0000000..6bc2088 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,41 @@ +//bfs +//o(n) space complexity +//o(n) time complexity +/* +// Definition for Employee. +class Employee { + public int id; + public int importance; + public List subordinates; +}; +*/ + +class Solution { + HashMap map = new HashMap<>(); + public int getImportance(List employees, int id) { + + int impTotal = 0; + + Queue q = new LinkedList<>(); + + for(Employee emp: employees){ + map.put(emp.id, emp); + } + q.add(id); + + + while(!q.isEmpty()){ + int size = q.size(); + int curr = q.poll(); + Employee currEmp = map.get(curr); + + impTotal = impTotal+currEmp.importance; + + for(int empId: currEmp.subordinates){ + q.add(empId); + + } + } + return impTotal; + } +}