From 8ea19e106a4c2314f346d505c3171bea5f1eded9 Mon Sep 17 00:00:00 2001 From: Sarthak Vaidya Date: Sun, 19 Oct 2025 02:45:36 -0400 Subject: [PATCH] Graph -1_Done --- Find the Town Judge.py | 18 +++++++++++++++++ The Maze.py | 45 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 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..08a84f7 --- /dev/null +++ b/Find the Town Judge.py @@ -0,0 +1,18 @@ +# Time Complexity : O(V + E) where V is the number of people and E is the number of realtionsips +# Space Complexity : O(V) +# Did this code successfully run on Leetcode : Yes +# Three line explanation of solution in plain english: We create an array having length equal to the number of people given. Everytime the person trusts somebody then we reduce the count by 1 and if the person is trusted by someone else we increase the count by 1. The index in the array having count 1 less than the total number of people will be the town judge. + +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + indegrees = [0] * (n + 1) + + for tr in trust: + indegrees[tr[0]] -= 1 + indegrees[tr[1]] += 1 + + for i in range(1, n + 1): + if indegrees[i] == n - 1: + return i + + return -1 diff --git a/The Maze.py b/The Maze.py new file mode 100644 index 0000000..aa28ea6 --- /dev/null +++ b/The Maze.py @@ -0,0 +1,45 @@ +# Time Complexity : O(m * n) +# Space Complexity : O(m * n) +# Did this code successfully run on Leetcode : Yes +# Three line explanation of solution in plain english: We use BFS to solve the problem. We traverse in one direction until we hit the stopping point. We make the stopping point equal to -1 to keep track that it has been visited. +import collections +class Solution: + def hasPath(self, maze, start, destination): + self.dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]] + self.m = len(maze) + self.n = len(maze[0]) + + q = collections.deque() + q.append([start[0], start[1]]) + maze[start[0]][start[1]] = -1 + + while q: + curr = q.popleft() + for dir in self.dirs: + r = dir[0] + curr[0] + c = dir[1] + curr[1] + + while r >= 0 and c >= 0 and r < self.m and c < self.m and maze[r][c] != 1: + r += dir[0] + c += dir[1] + + r -= dir[0] + c -= dir[1] + + if r == destination[0] and c == destination[1]: + return True + if maze[r][c] != -1: + maze[r][c] = -1 + q.append([r, c]) + return False + +if __name__ =="__main__": + maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]] + start = [0,4] + destination = [4,4] + + sol = Solution() + result = sol.hasPath(maze, start, destination) + print("Result: ", result) + +