From 9e2fed3582692a5c45b413f598a38d46fc83249c Mon Sep 17 00:00:00 2001 From: Hardik Prajapati Date: Sun, 26 Oct 2025 15:22:48 -0700 Subject: [PATCH] Graph1:All Done --- Find the Town Judge.py | 27 +++++++++++++++ The Maze.py | 79 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 Find the Town Judge.py create mode 100644 The Maze.py diff --git a/Find the Town Judge.py b/Find the Town Judge.py new file mode 100644 index 0000000..551d401 --- /dev/null +++ b/Find the Town Judge.py @@ -0,0 +1,27 @@ +''' +Solution : In-Degrees array + For a relationship a-->Trusts-->b + - +1 for b + - -1 for a + At the end, if in_degrees of a person == n-1, we found the judge +Time Complexity: O(N) +Space Complexity: O(N) +''' +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + in_degrees = [0]*n + + for relationship in trust: + a = relationship[0] + b = relationship[1] + + # a trusts b (people are 1->n indexed) + in_degrees[b-1]+=1 # increse count of people trusting b + in_degrees[a-1]-=1 # decrease count of 'a' as it's trusting someone + + for person_label in range(len(in_degrees)): + if in_degrees[person_label]==n-1: # n-1 people trusting and this person not trusting anyone else + return person_label+1 # Found judge. + + return -1 # No Judge + \ No newline at end of file diff --git a/The Maze.py b/The Maze.py new file mode 100644 index 0000000..478b1f5 --- /dev/null +++ b/The Maze.py @@ -0,0 +1,79 @@ +''' +Solution: BFS +Time complexity: O(m*n) +Space Complexity: O(m*n) +''' +class Solution: + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: + rows = len(maze) + cols = len(maze[0]) + + bfs_queue = deque() + + bfs_queue.append(start) + maze[start[0]][start[1]] = 2 # mark visited + + while bfs_queue: + parent_row, parent_col = bfs_queue.popleft() + + # Try rolling ball to right: + row = parent_row + col = parent_col + + while col=0 and maze[row][col]!=1: + col-=1 + col=col+1 # where ball stopped + + if [row,col]==destination: # ball stoped at target + return True + + if maze[row][col]!=2: + bfs_queue.append([row,col]) + maze[row][col]=2 + + # Try rolling ball upwards: + row = parent_row + col = parent_col + + while row>=0 and maze[row][col]!=1: + row-=1 + row=row+1 # where ball stopped + + if [row,col]==destination: # ball stoped at target + return True + + if maze[row][col]!=2: + bfs_queue.append([row,col]) + maze[row][col]=2 + + return False \ No newline at end of file