var x:(Array<Array<Char>>,String)->Boolean={b,s->fun f(s:String,x:Int,y:Int):Boolean{if(b[x][y]!=s[0])
return 0>1
if(s.length<2)
return 1>0
val v=b[x][y]
b[x][y]='Z'
try{return(-1..1).map{x+it}.flatMap{t->(-1..1).map{y+it}.map{t to it}}.filter{(X,Y)->(x-X)*(x-X)+(y-Y)*(y-Y)==1&&X in b.indices&&Y in b[0].indices&&f(s.substring(1),X,Y)}.any()}finally{b[x][y]=v}}
b.indices.any{x->(0..b[0].size-1).any{f(s,x,it)}}}
美化
var x: (Array<Array<Char>>, String) -> Boolean = { b, s ->
fun f(s: String, x: Int, y: Int): Boolean {
if (b[x][y] != s[0])
return 0 > 1
if (s.length < 2)
return 1 > 0
val v = b[x][y]
b[x][y] = 'Z'
try {
return (-1..1).map{ x + it }
.flatMap { t -> (-1..1).map{y+it}.map { t to it } }
.filter { (X, Y) ->
(x - X)*(x - X) + (y - Y)*(y - Y) == 1 &&
X in b.indices && Y in b[0].indices &&
f(s.substring(1), X, Y) }
.any()
} finally {
b[x][y] = v
}
}
b.indices.any { x -> (0..b[0].size - 1).any { f(s, x, it) } }
}
テスト
var x:(Array<Array<Char>>,String)->Boolean={b,s->fun f(s:String,x:Int,y:Int):Boolean{if(b[x][y]!=s[0])
return 0>1
if(s.length<2)
return 1>0
val v=b[x][y]
b[x][y]='Z'
try{return(-1..1).map{x+it}.flatMap{t->(-1..1).map{y+it}.map{t to it}}.filter{(X,Y)->(x-X)*(x-X)+(y-Y)*(y-Y)==1&&X in b.indices&&Y in b[0].indices&&f(s.substring(1),X,Y)}.any()}finally{b[x][y]=v}}
b.indices.any{x->(0..b[0].size-1).any{f(s,x,it)}}}
data class Test(val board: String, val snake: String, val output: Boolean)
val tests = listOf(
Test("""01010
|10101
|01010
|10101
|01010""", "0101010101010101010101010", true),
Test("""01110
|01100
|10010
|10110
|01101""", "011111000110100", true),
Test("""0""", "0", true),
Test("""10
|01""", "1010", true),
Test("""100
|010
|001""", "100010001", true),
Test("""00000
|00000
|00000
|00000
|00000""", "1", false),
Test("""10101
|01010
|10101
|01010
|10101""", "11", false),
Test("""100
|010
|001""", "111", false),
Test("""10001
|01010
|00100
|01010
|10001""", "1000100010001000101010100", false)
)
fun main(args: Array<String>) {
tests.filter {(board, snake, expected) ->
val boardR = board.trimMargin().lines().map { it.toCharArray().toTypedArray() }.toTypedArray()
val result = x(boardR, snake)
result != expected
}.forEach { throw AssertionError(it) }
println("Test Passed")
}