• + 0 comments

    In swift

    let N = 10
    
    func field2str(_ field: [[Character]]) -> String {
    return field.map { String($0) }.joined(separator: "\n")
    }
    
    struct Position: Equatable, Hashable {
        let i: Int
        let j: Int
        let di: Int
        let dj: Int
    }
    
    func solve(_ field: inout [[Character]], _ words: [String], _ positions: Set<Position>) {
        if words.isEmpty {
            print(field2str(field))
            return 
        }
    
        var words = words
        let word = words.removeLast()
    
        for position in positions {
            var (i, j, di, dj) = (position.i, position.j, position.di, position.dj)
            var goFurther = true
            var nextField = field
    
            for letter in word {
                if i >= N || j >= N || (nextField[i][j] != "-" && nextField[i][j] != letter) {
                    goFurther = false
                    break
                }
    
                nextField[i][j] = letter
                i += di
                j += dj
            }
    
            if i < N && j < N && nextField[i][j] == "-" {
                goFurther = false
            }
    
            if goFurther {
                var nextPositions = positions
                nextPositions.remove(position)
                solve(&nextField, words, nextPositions)
            }
        }
    }
    
    func main() {
        var field = [[Character]]()
        for _ in 0..<N {
            let row = Array(readLine()!)
            field.append(row)
        }
    
        let input = readLine()!
        let words = input.split(separator: ";").map { String($0) }
    
        var positions = Set<Position>()
    
        for i in 0..<N {
            for j in 0..<N {
                if field[i][j] == "-" {
                    if (i == 0 || field[i - 1][j] != "-") && (i == N - 1 || field[i + 1][j] == "-") {
                        positions.insert(Position(i: i, j: j, di: 1, dj: 0))
                    }
                    if (j == 0 || field[i][j - 1] != "-") && (j == N - 1 || field[i][j + 1] == "-") {
                        positions.insert(Position(i: i, j: j, di: 0, dj: 1))
                    }
                }
            }
        }
    
        solve(&field, words, positions)
    }
    
    main()