From 63702cae6f1266eaca26591b27c6f2858b5352dd Mon Sep 17 00:00:00 2001 From: yashhh-23 Date: Fri, 31 Jul 2026 19:52:44 +0530 Subject: [PATCH] completed graph 1 --- findjugde.java | 27 +++++++++++++++++++++++++++ maze.java | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 findjugde.java create mode 100644 maze.java diff --git a/findjugde.java b/findjugde.java new file mode 100644 index 0000000..19fc599 --- /dev/null +++ b/findjugde.java @@ -0,0 +1,27 @@ +// Time Complexity : O(n+e) where n is the number of nodes and e is the number of edges +// Space Complexity : O(n) for storing the inDegree and outDegree arrays +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : having the thought of indegree and outdegree of the nodes + +// Your code here along with comments explaining your approach: started with the idea of indegree and outdegree of the nodes. The judge will have indegree of n-1 and outdegree of 0. So we can keep track of indegree and outdegree of each node and return the node which has indegree of n-1 and outdegree of 0. +class Solution { + public int findJudge(int n, int[][] trust) { + int []inDegree=new int[n+1]; + int []outDegree=new int[n+1]; + for(int[]relation:trust) + { + int a=relation[0]; + int b= relation[1]; + outDegree[a]++; + inDegree[b]++; + } + for(int i=1;i<=n;i++) + { + if(outDegree[i]==0 && inDegree[i]==n-1) + { + return i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/maze.java b/maze.java new file mode 100644 index 0000000..3ddc238 --- /dev/null +++ b/maze.java @@ -0,0 +1,43 @@ +// Time Complexity : O(n*m) where n is the number of rows and m is the number of columns +// Space Complexity : O(n*m) for the queue and the modified maze array +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : understanding the ball rolling mechanism and ensuring the ball stops at the destination +// Your code here along with comments explaining your approach: used BFS to explore the maze. The ball can roll in four directions until it hits a wall. For each direction, I keep rolling the ball until it can't go further, then check if it has reached the destination. If not, I add the new position to the queue for further exploration. I also mark visited positions in the maze to avoid cycles. +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; + + Queue q = new LinkedList<>(); + q.add(new int[]{start[0], start[1]}); + maze[start[0]][start[1]] = -1; + + while(!q.isEmpty()){ + int[] curr = q.poll(); + for(int[] dir: dirs){ + int r = dir[0] + curr[0]; + int c = dir[1] + curr[1]; + + while(r>=0 && c>=0 && r