Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 3, 2024 18:51
Show Gist options
  • Save tatsuyax25/c184f4e821b4f5325bc21e83bbd1f8fc to your computer and use it in GitHub Desktop.
Save tatsuyax25/c184f4e821b4f5325bc21e83bbd1f8fc to your computer and use it in GitHub Desktop.
var exist = function(board, word) {
const dfs = (i, j, k) => {
// Base case: If k reaches the end of the word, return True
if (k === word.length) {
return true;
}
// Check if the current cell is out of bounds or does not match the word
if (
i < 0 ||
i >= board.length ||
j < 0 ||
j >= board[0].length ||
board[i][j] !== word[k]
) {
return false;
}
// Mark the current cell as visited (temporarily change its value)
const temp = board[i][j];
board[i][j] = '/'; // Use any character to indicate visited cell
// Explore adjacent cells (up, down, left, right)
const found =
dfs(i + 1, j, k + 1) ||
dfs(i - 1, j, k + 1) ||
dfs(i, j + 1, k + 1) ||
dfs(i, j - 1, k + 1);
// Restore the original value of the cell
board[i][j] = temp;
return found;
};
// Iterate through each cell in the grid
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
if (board[i][j] === word[0] && dfs(i, j, 0)) {
return true;
}
}
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment