Skip to content

Commit 53a4a17

Browse files
authored
Update 0099.岛屿的数量广搜.md: Add Scala script for the counting island puzzle using BFS algo
1 parent 00c0269 commit 53a4a17

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

problems/kamacoder/0099.岛屿的数量广搜.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,55 @@ main();
499499
### Swift
500500

501501
### Scala
502+
```scala
503+
import scala.collection.mutable.Queue
504+
import util.control.Breaks._
505+
506+
// Dev on LeetCode: https://leetcode.cn/problems/number-of-islands/description/
507+
object Solution {
508+
def numIslands(grid: Array[Array[Char]]): Int = {
509+
val row = grid.length
510+
val col = grid(0).length
511+
val dir = List((-1,0), (0,-1), (1,0), (0,1)) // 四个方向
512+
var visited = Array.fill(row)(Array.fill(col)(false))
513+
var counter = 0
514+
var que = Queue.empty[Tuple2[Int, Int]]
515+
516+
(0 until row).map{ r =>
517+
(0 until col).map{ c =>
518+
breakable {
519+
if (!visited(r)(c) && grid(r)(c) == '1') {
520+
que.enqueue((r, c))
521+
visited(r)(c) // 只要加入队列,立刻标记
522+
} else break // 不是岛屿不进入queue,也不记录
523+
524+
while (!que.isEmpty) {
525+
val cur = que.head
526+
que.dequeue()
527+
val x = cur(0)
528+
val y = cur(1)
529+
dir.map{ d =>
530+
val nextX = x + d(0)
531+
val nextY = y + d(1)
532+
breakable {
533+
// 越界就跳过
534+
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col) break
535+
if (!visited(nextX)(nextY) && grid(nextX)(nextY) == '1') {
536+
visited(nextX)(nextY) = true // 只要加入队列,立刻标记
537+
que.enqueue((nextX, nextY))
538+
}
539+
}
540+
}
541+
}
542+
counter = counter + 1 // 找完一个岛屿后记录一下
543+
}
544+
}
545+
}
546+
547+
counter
548+
}
549+
}
550+
```
502551

503552
### C#
504553

0 commit comments

Comments
 (0)