1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
var exist = function(board, word) { let height = board.length; let width = board[0].length; let result = false; for(let x = 0; x < height; x++) { for(let y = 0; y < width; y++) { if (board[x][y] === word[0]) { result = result || searchDFS(board, [ x, y ], shiftWord(word), [[x,y]]) } } } return result; };
var searchDFS = function (board, [x,y], word, useList = []) { const list = [...useList]; let result = false; if(!word || !word.length) { return true; }
if(x > 0 && board[x-1][y] === word[0] && !positionInList([x-1,y], list)) { const l = [...list] l.push([x-1, y]); result = result || searchDFS(board, [x-1,y], shiftWord(word), l); }
if (x < board.length-1 && board[x+1][y] === word[0] && !positionInList([x+1,y], list)) { const l = [...list] l.push([x+1, y]); result = result || searchDFS(board, [x+1,y], shiftWord(word), l); }
if (y > 0 && board[x][y-1] === word[0] && !positionInList([x,y-1], list)) { const l = [...list] l.push([x, y-1]); result = result || searchDFS(board, [x,y-1], shiftWord(word), l); }
if (y < board[0].length-1 && board[x][y+1] === word[0] && !positionInList([x,y+1], list)) { const l = [...list] l.push([x, y+1]); result = result || searchDFS(board, [x,y+1], shiftWord(word), l); }
return result; }
var positionInList = function ([x, y], list = []) { return list.some(([oX, oY]) => (oX === x && oY === y)) }
var shiftWord = function (word) { return Array.prototype.slice.call(word, 1).join('') }
|