LeetCode-in-Scala.github.io

Medium

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCCED”

Output: true

Example 2:

Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “SEE”

Output: true

Example 3:

Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCB”

Output: false

Constraints:

Follow up: Could you use search pruning to make your solution faster with a larger board?

Solution

object Solution {
    private val directions = Array(Array(-1, 0), Array(1, 0), Array(0, -1), Array(0, 1))
    private var numRows, numCols = 0

    def exist(board: Array[Array[Char]], word: String): Boolean = {
        if (board.length == 0) return false
        if (word.isEmpty) return true
        numRows = board.length
        numCols = board(0).length
        var result = false
        for (row <- 0 until numRows) {
            for (col <- 0 until numCols) {
                if (board(row)(col) == word(0)) {
                    result = backTracking(board, row, col, word, 0)
                    if (result) return true
                }
            }
        }
        result
    }

    private def backTracking(board: Array[Array[Char]], row: Int, col: Int, word: String, index: Int): Boolean = {
        if (index >= word.length) return true
        if (row < 0 || row >= numRows || col < 0 || col >= numCols || board(row)(col) != word(index) || board(row)(col) == '0') {
            return false
        }
        val originalValue = board(row)(col)
        board(row)(col) = '0'
        var output = false
        for (dir <- directions) {
            val newRow = row + dir(0)
            val newCol = col + dir(1)
            output = backTracking(board, newRow, newCol, word, index + 1)
            if (output) return true
        }
        board(row)(col) = originalValue
        output
    }
}