Skip to content

Commit 4135008

Browse files
committed
Added 207-Course-Schedule.kt and 417-Pacific-Atlantic-Waterflow.kt
1 parent 7b13263 commit 4135008

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

kotlin/207-Course-Schedule.kt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
3+
4+
if (prerequisites.isEmpty()) return true
5+
6+
val nodes = mutableMapOf<Int, MutableList<Int>>()
7+
prerequisites.forEach {
8+
val (v, w) = it
9+
nodes.getOrPut(v) { mutableListOf<Int>() } += w
10+
}
11+
12+
val visited = mutableSetOf<Int>()
13+
val visitedInCurrentStack = mutableSetOf<Int>()
14+
var hasCycle = false
15+
16+
fun traverse(startNode: Int) {
17+
18+
visited.add(startNode)
19+
visitedInCurrentStack.add(startNode)
20+
21+
for (v in nodes[startNode].orEmpty()) {
22+
if (!visited.contains(v)) {
23+
traverse(v)
24+
} else if (visitedInCurrentStack.contains(v)) {
25+
hasCycle = true
26+
return
27+
}
28+
}
29+
30+
visitedInCurrentStack.remove(startNode)
31+
}
32+
33+
for (key in nodes.keys) {
34+
traverse(key)
35+
}
36+
37+
return !hasCycle
38+
}
39+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
3+
val dirs = arrayOf(intArrayOf(0,1),
4+
intArrayOf(0,-1),
5+
intArrayOf(1,0),
6+
intArrayOf(-1,0))
7+
8+
fun pacificAtlantic(grid: Array<IntArray>): List<List<Int>> {
9+
if(grid.size == 0) return emptyList()
10+
val result = mutableListOf<List<Int>>()
11+
12+
val pacific = Array(grid.size) { BooleanArray(grid[0].size) }
13+
val atlantic = Array(grid.size) { BooleanArray(grid[0].size) }
14+
15+
for(i in 0 until grid.size) {
16+
dfs(grid, Integer.MIN_VALUE, i, 0, pacific)
17+
dfs(grid, Integer.MIN_VALUE, i, grid[0].size - 1, atlantic)
18+
}
19+
20+
for(i in 0 until grid[0].size) {
21+
dfs(grid, Integer.MIN_VALUE, 0, i, pacific)
22+
dfs(grid, Integer.MIN_VALUE, grid.size - 1, i, atlantic)
23+
}
24+
25+
for(i in 0 until grid.size) {
26+
for(j in 0 until grid[0].size) {
27+
if(atlantic[i][j] && pacific[i][j]) result.add(listOf(i, j))
28+
}
29+
}
30+
31+
return result
32+
}
33+
34+
private fun dfs(grid: Array<IntArray>, height: Int, i: Int, j: Int, visited: Array<BooleanArray>) {
35+
if(i < 0 || i >= grid.size || j < 0 || j >= grid[0].size || grid[i][j] < height || visited[i][j]) return
36+
37+
visited[i][j] = true
38+
39+
dirs.forEach { dir ->
40+
dfs(grid, grid[i][j], dir[0] + i, dir[1] + j, visited)
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)