diff --git a/employee-importance.cs b/employee-importance.cs new file mode 100644 index 0000000..df2bf42 --- /dev/null +++ b/employee-importance.cs @@ -0,0 +1,41 @@ +/* +// Definition for Employee. +class Employee { + public int id; + public int importance; + public IList subordinates; +} +*/ + +// Time Complexity: O(n) +// Space Complexity: O(n) + +// Build a dictionary to quickly map employee id & Employee object. +// Use a queue (BFS) starting from the given id to traverse the employee and all their subordinates. +// Sum the importance of each visited employee and return the total. +class Solution +{ + public int GetImportance(IList employees, int id) + { + Queue q = new(); + q.Enqueue(id); + int result = 0; + Dictionary dict = new(); + foreach (var emp in employees) + { + dict.Add(emp.id, emp); + } + while (q.Count != 0) + { + int cid = q.Dequeue(); + Employee abc = dict[cid]; + result += abc.importance; + foreach (var ab in abc.subordinates) + { + q.Enqueue(ab); + } + + } + return result; + } +} \ No newline at end of file diff --git a/rotting-oranges.cs b/rotting-oranges.cs new file mode 100644 index 0000000..18b6858 --- /dev/null +++ b/rotting-oranges.cs @@ -0,0 +1,68 @@ + +// Time Complexity: O(m × n) +// Space Complexity: O(m × n) + +// Approach +// Initially add all rotten oranges to a queue and count fresh oranges (multi-source BFS). +// Perform BFS level by level; each level represents one minute, rotting adjacent fresh oranges. +// If all fresh oranges rot, return total minutes taken; otherwise return -1. +public class Solution +{ + public int OrangesRotting(int[][] grid) + { + + int[][] directions = new int[][]{new int[]{1,0},new int[]{-1,0}, + new int[]{0,1},new int[]{0,-1}}; + int time = 0; + int freshOranges = 0; + int rows = grid.Length; + int cols = grid[0].Length; + Queue q = new(); + + for (int i = 0; i < rows; i++) + { + for (int j = 0; j < cols; j++) + { + if (grid[i][j] == 2) + { + q.Enqueue(new int[] { i, j }); + } + if (grid[i][j] == 1) + { + freshOranges++; + } + } + } + if (freshOranges == 0) return 0; + + while (q.Count > 0) + { + int size = q.Count(); + for (int i = 0; i < size; i++) + { + int[] cur = q.Dequeue(); + int startRow = cur[0]; + int startCol = cur[1]; + + foreach (int[] dir in directions) + { + int curRow = startRow + dir[0]; + int curCol = startCol + dir[1]; + + if ((curRow >= 0 && curRow < rows) && (curCol >= 0 && curCol < cols) + && grid[curRow][curCol] == 1) + { + grid[curRow][curCol] = 2; + freshOranges--; + q.Enqueue(new int[] { curRow, curCol }); + } + } + } + time++; + } + return freshOranges == 0 ? time - 1 : -1; + } +} + + +