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
23 changes: 23 additions & 0 deletions findthetown.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
43 changes: 43 additions & 0 deletions maze.java
Original file line number Diff line number Diff line change
@@ -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<m && c<n && maze[r][c] != 1){
r += dir[0];
c += dir[1];
}

r -= dir[0];
c -= dir[1];
if(dfs(maze, r, c, destination)) return true;
}

return false;
}
}