Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions findjugde.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
43 changes: 43 additions & 0 deletions maze.java
Original file line number Diff line number Diff line change
@@ -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<int[]> 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<m && c<n && maze[r][c] != 1){
r += dir[0];
c += dir[1];
}

r -= dir[0];
c -= dir[1];

if(r == destination[0] && c == destination[1]) return true;
if(maze[r][c] != -1){
q.add(new int[]{r,c});
maze[r][c] = -1;
}
}
}

return false;
}
}