79. Word Search

Description

Given a 2D board and a word, find if the word exists in the grid.

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

For example, Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Solution

/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
var exist = function(board, word) {
    "use strict";
    let table = [];
    for (let i = 0; i < board.length; i++) {
        table[i] = [];
        for (let j = 0; j < board[i].length; j++) {
            table[i][j] = false;
        }
    }
    /** 
     * Search the adjacent cells for the target word
     * @param {string} word
     * @param {number} i: The row number of current cell
     * @param {number} j: The column number of current cell
     * @return {boolean}
     */
    function search(word, i, j) {
        if (table[i][j]) {
            return false;
        }
        if (word[0] === board[i][j]) {
            let nextWord = word.slice(1);
            if (!nextWord.length) {
                return true;
            }
            table[i][j] = true;
            // Move right
            if (j+1 < board[i].length) {
                if (search(nextWord, i, j+1)) {
                    return true;
                }
            }
            // Move down
            if (i+1 < board.length) {
                if (search(nextWord, i+1, j)) {
                    return true;
                }
            }
            // Move left
            if (j-1 >= 0) {
                if (search(nextWord, i, j-1)) {
                    return true;
                }
            }
            // Move up
            if (i-1 >= 0) {
                if (search(nextWord, i-1, j)) {
                    return true;
                }
            }
        }
        table[i][j] = false;
        return false;
    }
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (search(word, i, j)) {
                return true;
            }
        }
    }
    return false;
};

results matching ""

    No results matching ""