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
61 changes: 61 additions & 0 deletions ball_in_maze.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Time Complexity : O(m * n) because each stopping point is visited at most once
// Space Complexity : O(m * n) for recursion stack in the worst case
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach in three sentences only
// We use DFS to explore all reachable stopping points in the maze.
// From each position, the ball rolls in a direction until it hits a wall, and only the stopping position is explored further.
// We mark visited stopping points to avoid revisiting the same state and prevent infinite loops.

class Solution {
int[][] dirs;
int m;
int 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) {

// destination reached
if(destination[0] == i && destination[1] == j) {
return true;
}

// already visited
if(maze[i][j] == -1) {
return false;
}

maze[i][j] = -1;

for(int[] dir : dirs) {

int r = i + dir[0];
int c = j + dir[1];

// roll until wall
while(r >= 0 && c >= 0 && r < m && c < n && maze[r][c] != 1) {
r += dir[0];
c += dir[1];
}

// move back to stopping point
r -= dir[0];
c -= dir[1];

if(dfs(maze, r, c, destination)) {
return true;
}
}

return false;
}
}
32 changes: 32 additions & 0 deletions town_judge.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time Complexity : O(n + m) where n is the number of people and m is the number of trust relationships
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach in three sentences only
// We use an indegree array to track the net trust score of every person.
// If a person trusts someone, their score decreases; if they are trusted by someone, their score increases.
// The town judge will have a score of n-1 because everyone trusts them and they trust nobody.

class Solution {
public int findJudge(int n, int[][] trust) {

int[] indegrees = new int[n + 1];

// build trust scores
for(int[] t : trust) {
indegrees[t[0]]--;
indegrees[t[1]]++;
}

// judge should have score n-1
for(int i = 1; i <= n; i++) {
if(indegrees[i] == n - 1) {
return i;
}
}

return -1;
}
}