单词搜索
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
1.
var exist = function (board, word) { let mark = []; let right = 0; let directs = [[0, 1], [0, -1], [1, 0], [-1, 0]]; for(let i=0;i<board.length;i++){ let demo = new Array(board[0].length).fill(0); mark.push(demo); } for(let i=0;i<board.length;i++){ for(let j=0 ;j<board[0].length;j++){ if(board[i][j]===word[0]){ mark[i][j] = 1; right ++; if(check(i,j,mark)){ return true; }else{ mark[i][j] = 0; right--; } } } } function check(i,j,mark){ if(right>= word.length){ return true; } if(right>= word.length){ return true; } for(let k =0;k<directs.length;k++){ let cur_i = i + directs[k][0]; let cur_j = j + directs[k][1]; if(cur_i>=0&&cur_i<board.length&&cur_j>=0&&cur_j<board[0].length&&mark[cur_i][cur_j]!=1&&board[cur_i][cur_j] == word[right]){ mark[cur_i][cur_j] = 1; right++; if(check(cur_i,cur_j,mark)){ return true; }else{ mark[cur_i][cur_j] = 0; right--; } } } return false; } return false; };
2.
var exist = function (board, word) { //越界处理 board[-1] = [] board.push([]) //寻找首个字母 for (let y = 0; y < board.length; y++) { for (let x = 0; x < board.length; x++) { if (word[0] === board[y][x] && backtrack(y, x, 0)) return true } } //回溯 function backtrack(y, x, i) { //回溯终止 if (i + 1 === word.length) return true //保存字母 var tmp = board[y][x] board[y][x] = false if (board[y][x + 1] === word[i + 1] && backtrack(y, x + 1, i + 1)) return true if (board[y][x - 1] === word[i + 1] && backtrack(y, x - 1, i + 1)) return true if (board[y + 1][x] === word[i + 1] && backtrack(y + 1, x, i + 1)) return true if (board[y - 1][x] === word[i + 1] && backtrack(y - 1, x, i + 1)) return true //复原字母 board[y][x] = tmp } return false };
实现:主要就是实现上下左右的回溯算法。
来源:https://leetcode-cn.com/problems/word-search/solution/javascript-by-shen-xia/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。