From d44ace07bd1a7f125baaafe60b988f50e4c55ca6 Mon Sep 17 00:00:00 2001 From: srilekhad Date: Wed, 17 Sep 2025 11:57:47 -0500 Subject: [PATCH] Done Graph-1 --- findthetown.java | 23 +++++++++++++++++++++++ maze.java | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 findthetown.java create mode 100644 maze.java diff --git a/findthetown.java b/findthetown.java new file mode 100644 index 0000000..266d543 --- /dev/null +++ b/findthetown.java @@ -0,0 +1,23 @@ +//Time Complexity: O(V + E), where V is the number of people and E is the number of trust relationships. +//SC: O(v) for the indegree array. + +//Create indegrees[1..n]; for each (a,b) do indegrees[a]-- (a trusts someone) and indegrees[b]++ (b is trusted). +//The judge (if any) must have indegrees[i] == n-1 (trusted by all others, trusts nobody). +//Scan 1..n to find and return that i; if none matches, return -1. + +class Solution { + public int findJudge(int n, int[][] trust) { + int[] indegrees = new int[n+1]; + + for(int[] tr: trust){ //O(E) + indegrees[tr[0]]--; + indegrees[tr[1]]++; + } + + for(int i=1; i<=n; i++){ //O(V) + if(indegrees[i] == n-1) return i; + } + + return -1; + } +} diff --git a/maze.java b/maze.java new file mode 100644 index 0000000..8937ca8 --- /dev/null +++ b/maze.java @@ -0,0 +1,43 @@ +//TC: O(m·n) — each DFS/BFS step may roll across a row/column, and each cell is settled once. +//SC: O(m·n) worst-case for recursion/visited marking. + +//From the start, roll in each of the 4 directions until hitting a wall, stop just before the wall. +//Recursively DFS from that stopping cell if not already visited. +//If you ever reach the destination, return true; if all paths fail, return false. + +class Solution { + int[][] dirs; + int m,n; + + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + this.dirs = new int[][]{{-1,0},{1,0},{0,1},{0,-1}}; + this.m = maze.length; + this.n = maze[0].length; + + return dfs(maze, start[0], start[1], destination); + } + + private boolean dfs(int[][] maze, int i, int j, int[] destination){ + //base case + if(destination[0] == i && destination[1] == j) return true; + + if(maze[i][j] == -1) return false; + + maze[i][j] = -1; + for(int[] dir: dirs){ + int r = dir[0] + i; + int c = dir[1] + j; + + while(r>=0 && c>=0 && r