Problems178
Search for a command to run...
Initialization
Look for "ABCCED" by starting at every cell whose letter matches the first character, then walking to neighbours in the order down, up, right, left.
DFS with Backtracking
1function func(board, i, j, word, k) {2 // Whole word matched3 if (k === word.length) return true;4 5 // Off the board, or wrong character6 if (i < 0 || j < 0 || i >= board.length ||7 j >= board[0].length || word[k] !== board[i][j]) {8 return false;9 }10 11 // Mark visited so this cell cannot be reused12 const temp = board[i][j];13 board[i][j] = ' ';14 15 const ans = func(board, i + 1, j, word, k + 1) ||//word: ABCCEDrows: 3cols: 416 func(board, i - 1, j, word, k + 1) ||17 func(board, i, j + 1, word, k + 1) ||18 func(board, i, j - 1, word, k + 1);19 20 // Restore on the way out21 board[i][j] = temp;22 return ans;23}24 25function exist(board, word) {26 for (let i = 0; i < board.length; i++) {27 for (let j = 0; j < board[0].length; j++) {28 if (board[i][j] === word[0]) {29 if (func(board, i, j, word, 0)) return true;30 }31 }32 }33 return false;34}