Skip to main content

Word Search II

Problem statement

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must 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 in a word.

Example 1:

Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]Output: ["eat","oath"]

Example 2:

Input: board = [["a","b"],["c","d"]], words = ["abcb"]Output: []

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter.
  • 1 <= words.length <= 3 * 104
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.

My solution

/**
* @param {character[][]} board
* @param {string[]} words
* @return {string[]}
*/
var findWords = function(board, words) {
const set = new Set(words);
const maxWordLength = Math.max(...words.map(v => v.length))
const result = new Set();
const firstChar = new Set(words.map(v => v.charAt(0)))

function dfs(matrix, words, row, column, word) {
if (row < 0 || column < 0 || row >= matrix.length || (matrix[row] && column >= matrix[row].length) || matrix[row][column] === undefined || word.length > maxWordLength) {
return;
}

const currentChar = matrix[row][column];
const newWord = word + currentChar
// console.log(newWord)

if (set.has(newWord) && !result.has(newWord)) {
result.add(newWord)
}

matrix[row][column] = undefined;

dfs(matrix, words, row + 1, column, newWord)
dfs(matrix, words, row - 1, column, newWord)
dfs(matrix, words, row, column + 1, newWord)
dfs(matrix, words, row, column - 1, newWord)


matrix[row][column] = currentChar;

}

for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
const char = board[i][j];
// console.log(char)
if (firstChar.has(char)) {
dfs(board, set, i, j, "")
}
}
}

return [...result]
};