Update 0099.岛屿的数量广搜.md: Add Scala script for the counting island puzzle using BFS algo

This commit is contained in:
Camille
2024-09-26 23:06:45 +08:00
committed by GitHub
parent 00c0269fe8
commit 53a4a17b8c

View File

@ -499,6 +499,55 @@ main();
### Swift
### Scala
```scala
import scala.collection.mutable.Queue
import util.control.Breaks._
// Dev on LeetCode: https://leetcode.cn/problems/number-of-islands/description/
object Solution {
def numIslands(grid: Array[Array[Char]]): Int = {
val row = grid.length
val col = grid(0).length
val dir = List((-1,0), (0,-1), (1,0), (0,1)) // 四个方向
var visited = Array.fill(row)(Array.fill(col)(false))
var counter = 0
var que = Queue.empty[Tuple2[Int, Int]]
(0 until row).map{ r =>
(0 until col).map{ c =>
breakable {
if (!visited(r)(c) && grid(r)(c) == '1') {
que.enqueue((r, c))
visited(r)(c) // 只要加入队列,立刻标记
} else break // 不是岛屿不进入queue也不记录
while (!que.isEmpty) {
val cur = que.head
que.dequeue()
val x = cur(0)
val y = cur(1)
dir.map{ d =>
val nextX = x + d(0)
val nextY = y + d(1)
breakable {
// 越界就跳过
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col) break
if (!visited(nextX)(nextY) && grid(nextX)(nextY) == '1') {
visited(nextX)(nextY) = true // 只要加入队列,立刻标记
que.enqueue((nextX, nextY))
}
}
}
}
counter = counter + 1 // 找完一个岛屿后记录一下
}
}
}
counter
}
}
```
### C#