1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| object WordSerach { def main(args: Array[String]): Unit = { val board = Array[Array[Char]]( Array('A', 'B', 'C', 'E') )
println(exist(board, "BC")) println(exist(board, "ABCCED")) println(exist(board, "ABCB")) }
def exist(board: Array[Array[Char]], word: String): Boolean = { val m = board.length if (m == 0) return false val n = board(0).length val selected = new mutable.HashSet[(Int, Int)]() for (i <- 0 until m) { for (j <- 0 until n) { if (board(i)(j) == word.charAt(0)) { selected.clear() val pos = (i, j) selected += pos if (dfs(board, selected, pos, word, 1)) { return true } } } } false }
def dfs(board: Array[Array[Char]], selected: mutable.HashSet[(Int, Int)], pos: (Int, Int), word: String, index: Int): Boolean = { if (index == word.length) { return true }
Array[(Int, Int)]( (pos._1, pos._2 - 1), (pos._1 - 1, pos._2), (pos._1, pos._2 + 1), (pos._1 + 1, pos._2) ).foreach(a => { if (0 <= a._1 && a._1 < board.length && 0 <= a._2 && a._2 < board(0).length) { if (!selected.contains(a) && board(a._1)(a._2) == word.charAt(index)) { selected += a if (dfs(board, selected, a, word, index + 1)) { return true } selected -= a } } })
false } }
|