Skip to content

Instantly share code, notes, and snippets.

@lskjdkf
Created June 21, 2022 19:03
Show Gist options
  • Save lskjdkf/fcf3c271d16c02a99ef17d0df9d4261a to your computer and use it in GitHub Desktop.
Save lskjdkf/fcf3c271d16c02a99ef17d0df9d4261a to your computer and use it in GitHub Desktop.
my solution for Word Search II problem (https://leetcode.com/problems/word-search-ii/). Probably has gigantic time complexity, so I'm 90% sure you can optimize the heck of it.
function* anf(length, base) {
let arr = new Array(length).fill(0);
while (true) {
yield arr;
let br = true;
for (let i = 0; i < length; i++) {
if (arr[i] != base - 1) {
++arr[i];
br = false;
break;
} else {
arr[i] = 0;
}
}
if (br)
break;
}
}
/**
* @param {character[][]} board
* @param {string[]} words
* @return {string[]}
*/
function findWords(board, words) {
const
m = board.length,
n = board[0].length,
max = words.reduce((acc, cur) => Math.max(acc, cur.length), 0);
words = new Set(words);
let ret = new Set;
for (let y = 0; y < m; y++)
for (let x = 0; x < n; x++) {
for (let l = 0; l < max; l++) {
for (let walks of anf(l, 4)) {
// check if valid, also construct coords
let walksCoords = new Array(l);
let
valid = true,
mx = x, my = y;
walksCoords[0] = [mx, my];
for (let i = 0; i < l; i++) {
// step
switch (walks[i]) {
case 0:
--mx;
break;
case 1:
++mx;
break;
case 2:
--my;
break;
default:
++my;
break;
}
// check
if (
walksCoords.some(v => v[0] == mx && v[1] == my) || // check if coord exists
!(0 <= mx && mx < n && 0 <= my && my < n) // check if out of bounds
) {
valid = false;
break;
}
// push
walksCoords[i + 1] = [mx, my];
}
if (valid) {
// construct string from walks
let str = '';
for (let i = 0; i < l + 1; i++)
str += board[walksCoords[i][1]][walksCoords[i][0]];
// check if in words
if (words.has(str)) {
ret.add(str);
}
}
}
}
}
return [...ret];
}
let
board = [
["o","a","a","n"],
["e","t","a","e"],
["i","h","k","r"],
["i","f","l","v"]
],
words = ["oath","pea","eat","rain"];
findWords(board, words);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment