Skip to content

Instantly share code, notes, and snippets.

@WilfredTA
Last active February 17, 2019 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WilfredTA/8813077504968052c1fc73b8a1809a21 to your computer and use it in GitHub Desktop.
Save WilfredTA/8813077504968052c1fc73b8a1809a21 to your computer and use it in GitHub Desktop.
The "dumb" version the backtracking algorithm for the word search problem on LeetCode
var exist = function(board, word) {
var seen = [];
var targetCharIdx = 0;
var result = {
found: false
};
existHelper(board, word, seen, result);
return result.found;
};
var existHelper = function(board, word, seen, result) {
if (word.length === seen.length) {
if (wordMatches(word, seen, board)) {
if (cellsAreUnique(seen)) {
if (cellsAreAdjacent(seen)) {
result.found = true;
}
}
}
} else {
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < board[0].length; j++) {
seen.push([i, j])
existHelper(board, word, seen, result)
seen.pop();
}
}
}
};
var cellsAreAdjacent = function(seen) {
var i = 0;
var j = 1;
var cellOne;
var cellTwo;
while (j < seen.length) {
cellOne = seen[i];
cellTwo = seen[j];
var diffOne = Math.abs(cellOne[0] - cellTwo[0]);
var diffTwo = Math.abs(cellOne[1] - cellTwo[1]);
if (!xor(diffOne === 1, diffTwo === 1)) {
return false;
}
j += 1;
i += 1;
}
return true;
};
var xor = function(option1, option2) {
return ((option1 || option2) && !(option1 && option2));
};
var cellsAreUnique = function(seen) {
var usedCoordinates = {};
var lookup = '';
for (var i = 0; i < seen.length; i++) {
lookup = seen[i][0].toString() + seen[i][1].toString();
if (usedCoordinates[lookup]) {
return false;
}
usedCoordinates[lookup] = true;
}
return true;
};
var wordMatches = function(word, seen, board) {
var constructedWord = '';
seen.forEach(function(coordinate) {
constructedWord += board[coordinate[0]][coordinate[1]];
});
return constructedWord === word;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment