思路分析
- 创建一个二维数组(表示地图)。
- 约定不同的数字表示不同的含义。元素的值,0:表示可以走还没走过,1:墙,2:表示可以走,3:表示已经走过了,但是是死路。
- 确定一个策略。下->右->上->左。
代码实现
package chapter18.recursive
object MiGong {
def main(args: Array[String]): Unit = {
val map = Array.ofDim[Int](8, 7)
for (i <- 0 until 7) {
map(0)(i) = 1
map(7)(i) = 1
}
for (i <- 0 until 8) {
map(i)(0) = 1
map(i)(6) = 1
}
map(3)(1) = 1
map(3)(2) = 1
for (i <- 0 until 8) {
for (j <- 0 until 7) {
print(map(i)(j) + " ")
}
println()
}
setWay(map, 1, 1)
println("\n----------------运行后------------------------\n")
for (i <- 0 until 8) {
for (j <- 0 until 7) {
print(map(i)(j) + " ")
}
println()
}
}
def setWay(map: Array[Array[Int]], i: Int, j: Int): Boolean = {
if (map(6)(5) == 2) {
return true
} else {
if (map(i)(j) == 0) {
map(i)(j) = 2
if (setWay(map, i + 1, j)) {
return true
} else if (setWay(map, i, j + 1)) {
return true
} else if (setWay(map, i - 1, j)) {
return true
} else if (setWay(map, i, j - 1)) {
return true
} else {
map(i)(j) = 3
return false
}
} else {
return false
}
}
}
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8eb32fc9e329d31293aeac119bd6886c.png)