From 5156c82ab402c0452f3dd97e0738f0b3cb000c1b Mon Sep 17 00:00:00 2001 From: Sahithipsl470 Date: Tue, 10 Mar 2026 19:52:31 -0400 Subject: [PATCH] "Graph-1 done" --- Problem-1.py | 25 +++++++++++++++++++++++++ Problem-2.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 Problem-1.py create mode 100644 Problem-2.py diff --git a/Problem-1.py b/Problem-1.py new file mode 100644 index 0000000..bafa782 --- /dev/null +++ b/Problem-1.py @@ -0,0 +1,25 @@ +# Time Complexity : O(n + t), t = number of trust pairs +# Space Complexity : O(n), to track trust counts +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# Explanation: +# 1. Track two counts for each person: number of people they trust and number of people who trust them. +# 2. The town judge trusts nobody (trusts count = 0) and is trusted by n-1 people. +# 3. Scan all people and return the one satisfying these conditions. Return -1 if none. + +from typing import List + +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + trusts = [0] * (n + 1) # number of people each person trusts + trusted_by = [0] * (n + 1) # number of people who trust each person + + for a, b in trust: + trusts[a] += 1 + trusted_by[b] += 1 + + for i in range(1, n + 1): + if trusts[i] == 0 and trusted_by[i] == n - 1: + return i + return -1 \ No newline at end of file diff --git a/Problem-2.py b/Problem-2.py new file mode 100644 index 0000000..e2532ad --- /dev/null +++ b/Problem-2.py @@ -0,0 +1,35 @@ +# Time Complexity : O(m * n), worst case visiting all cells +# Space Complexity : O(m * n), visited matrix +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# Explanation: +# 1. Use DFS to explore the maze. From a cell, roll in each direction until hitting a wall. +# 2. Only mark the stopping cell as visited and continue DFS from there. +# 3. If we reach the destination, return True. Otherwise, continue exploring other directions. +# 4. Return False if all paths have been explored. + +from typing import List + +class Solution: + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: + m, n = len(maze), len(maze[0]) + visited = [[False] * n for _ in range(m)] + + def dfs(x, y): + if [x, y] == destination: + return True + if visited[x][y]: + return False + visited[x][y] = True + for dx, dy in [(0,1),(1,0),(0,-1),(-1,0)]: + nx, ny = x, y + # roll until hitting wall + while 0 <= nx + dx < m and 0 <= ny + dy < n and maze[nx + dx][ny + dy] == 0: + nx += dx + ny += dy + if dfs(nx, ny): + return True + return False + + return dfs(start[0], start[1]) \ No newline at end of file