[LeetCode][JavaScript]Word Search
2015-12-03 16:25
239 查看
Word Search
Given a 2D board and a word, find if the word exists in the grid.The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
word =
"ABCCED", -> returns
true,
word =
"SEE", -> returns
true,
word =
"ABCB", -> returns
false.
https://leetcode.com/problems/word-search/
找单词,DFS。
每一步都可以上下左右四个方向走,开一个数组visited记录已经走过的格子。
/** * @param {character[][]} board * @param {string} word * @return {boolean} */ var exist2 = function(board, word) { if(word === "") return true; if(board.length === 0) return word === "" ? true : false; var i, j, rowLen = board.length, colLen = board[0].length, visited = []; for(i = 0; i < rowLen; i++) visited[i] = []; for(i = 0; i < board.length; i++) for(j = 0; j < colLen; j++) if(board[i][j] === word[0]) if(dfs(0, i, j)) return true; return false; function dfs(index, x, y){ if(index === word.length - 1) return true; visited[x][y] = true; if(dfsNeighbor(index, x - 1, y)) return true; //up if(dfsNeighbor(index, x + 1, y)) return true; //down if(dfsNeighbor(index, x, y - 1)) return true; //left if(dfsNeighbor(index, x, y + 1)) return true; //right visited[x][y] = false; return false; } function dfsNeighbor(index, x, y){ if(!board[x] || !board[x][y]) return false; if(!visited[x][y] && board[x][y] === word[index + 1]){ return dfs(index + 1, x, y); } return false; } };
优化了一下,不用开visited数组,直接用入参的board记录是否访问过。
/** * @param {character[][]} board * @param {string} word * @return {boolean} */ var exist = function(board, word) { if(word === "") return true; var i, j; for(i = 0; i < board.length; i++) for(j = 0; j < board[i].length; j++) if(board[i][j] === word[0]) if(dfs(0, i, j)) return true; return false; function dfs(index, x, y){ if(index === word.length) return true; if(!board[x] || !board[x][y]) return false; if(board[x][y] !== '#' && board[x][y] === word[index]){ var ch = board[x][y]; board[x][y] = '#'; if(dfs(index + 1, x - 1, y)) return true; //up if(dfs(index + 1, x + 1, y)) return true; //down if(dfs(index + 1, x, y - 1)) return true; //left if(dfs(index + 1, x, y + 1)) return true; //right board[x][y] = ch; } return false; } };
相关文章推荐
- routes.js剖析
- 谈谈JavaScript的2种主要继承方式
- JavaScript Window History与Window Navigator与JavaScript 消息框
- js输入框对金额的匹配
- 推荐一个用于压缩图片的JS插件:localResizeIMG
- javascript,css3加载动画
- javascript第四弹——变量、作用域、内存
- JavaScript Window - 浏览器对象模型与Window Screen与Window Location
- 破解由于异步执行而导致的JS插件未加载就使用的问题
- JS上传图片本地实时预览缩略图
- Javascript操作DOM常用API总结
- js.prototype最深刻的理解
- JavaScript_DOM编程艺术第二版学习笔记-第5章
- js控制浏览器后退
- escape()、encodeURI()、encodeURIComponent()区别详解
- JS根据动态生成的字符串,验证是否存在对应function并执行
- JS正则获取参数值
- 使用 后退键/history.back()出现"警告: 网页已过期的解决办法"
- xStream完美转换XML、JSON
- dTree JS 基本用法