Skip to content

Commit 9a4dab8

Browse files
authored
Update 0099.岛屿的数量深搜.md Add Scala code to solve counting islands problem on LeetCode
1 parent e7c8d01 commit 9a4dab8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: problems/kamacoder/0099.岛屿的数量深搜.md

+40
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,46 @@ const dfs = (graph, visited, x, y) => {
412412
### Swift
413413

414414
### Scala
415+
```scala
416+
import util.control.Breaks._
417+
418+
object Solution {
419+
val dir = List((-1,0), (0,-1), (1,0), (0,1)) // 四个方向
420+
421+
def dfs(grid: Array[Array[Char]], visited: Array[Array[Boolean]], row: Int, col: Int): Unit = {
422+
(0 until 4).map { x =>
423+
val nextR = row + dir(x)(0)
424+
val nextC = col + dir(x)(1)
425+
breakable {
426+
if(nextR < 0 || nextR >= grid.length || nextC < 0 || nextC >= grid(0).length) break
427+
if (!visited(nextR)(nextC) && grid(nextR)(nextC) == '1') {
428+
visited(nextR)(nextC) = true // 经过就记录
429+
dfs(grid, visited, nextR, nextC)
430+
}
431+
}
432+
}
433+
}
434+
435+
def numIslands(grid: Array[Array[Char]]): Int = {
436+
val row = grid.length
437+
val col = grid(0).length
438+
var visited = Array.fill(row)(Array.fill(col)(false))
439+
var counter = 0
440+
441+
(0 until row).map{ r =>
442+
(0 until col).map{ c =>
443+
if (!visited(r)(c) && grid(r)(c) == '1') {
444+
visited(r)(c) = true // 经过就记录
445+
dfs(grid, visited, r, c)
446+
counter += 1
447+
}
448+
}
449+
}
450+
451+
counter
452+
}
453+
}
454+
```
415455

416456
### C#
417457

0 commit comments

Comments
 (0)