LeetCode in Kotlin

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

class Solution {
    private fun backtrace(
        board: Array<CharArray>,
        visited: Array<BooleanArray>,
        word: String,
        index: Int,
        x: Int,
        y: Int,
    ): Boolean {
        if (index == word.length) {
            return true
        }
        if (x < 0 || x >= board.size || y < 0 || y >= board[0].size || visited[x][y]) {
            return false
        }
        visited[x][y] = true
        return if (word[index] == board[x][y]) {
            val res = (
                backtrace(board, visited, word, index + 1, x, y + 1) ||
                    backtrace(board, visited, word, index + 1, x, y - 1) ||
                    backtrace(board, visited, word, index + 1, x + 1, y) ||
                    backtrace(board, visited, word, index + 1, x - 1, y)
                )
            if (!res) {
                visited[x][y] = false
            }
            res
        } else {
            visited[x][y] = false
            false
        }
    }

    fun exist(board: Array<CharArray>, word: String): Boolean {
        val visited = Array(board.size) {
            BooleanArray(
                board[0].size,
            )
        }
        for (i in board.indices) {
            for (j in board[0].indices) {
                if (backtrace(board, visited, word, 0, i, j)) {
                    return true
                }
            }
        }
        return false
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy