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 week09/course_schedule.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Time complexity: O(N), N = Number of courses.
// Space complexity: O(N), N = Number of courses.

bool hasCycle(vector<int> &col, vector<vector<int>> &graph, int u){
col[u] = 1;
bool status = false;
for(auto v: graph[u]){
if(col[v] == 1) status = true;
else if(col[v] == 0){
status |= hasCycle(col, graph, v);
}
}
col[u] = 2;
return status;
}

bool canFinish(int numCourses, vector<vector<int>> &prerequisites){
vector<vector<int>> graph(numCourses);
vector<int> col(numCourses, 0);
for(auto pre: prerequisites){
graph[pre[1]].push_back(pre[0]);
}
for(int i = 0; i < numCourses; i++){
if(hasCycle(col, graph, i)) return false;
}
return true;
}
7 changes: 7 additions & 0 deletions week09/maximum_depth_of_a_binary_tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Time complexity: O(N), N = Number of nodes.
// Space complexity: O(1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually the space complexity is O(H) where H = depth of the recursion.


int maxDepth(TreeNode* root, int depth = 0){
if(!root) return depth;
return max(maxDepth(root->left, depth + 1), maxDepth(root->right, depth + 1));
}
31 changes: 31 additions & 0 deletions week09/number_of_islands.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time complexity: O(M * N), M = Number of rows, N = Number of columns of the grid.
// Space complexity: O(1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing as above.


int dr[4] = {-1, 0, 1, 0};
int dc[4] = {0, 1, 0, -1};

void dfs(vector<vector<char>> &grid, int row, int col){
int r = grid.size();
int c = grid[0].size();
if(row == r || col == c || row < 0 || col < 0) return;
if(grid[row][col] == '0' || grid[row][col] == '2') return;
grid[row][col] = '2';
for(int i = 0; i < 4; i++){
dfs(grid, row + dr[i], col + dc[i]);
}
}

int numIslands(vector<vector<char>> &grid){
int row = grid.size();
int col = grid[0].size();
int count = 0;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(grid[i][j] == '1'){
count++;
dfs(grid, i, j);
}
}
}
return count;
}