79 Word Search
2015-10-28 21:23
288 查看
题目链接:https://leetcode.com/problems/word-search/
题目:
解题思路:
这道题考点在图的深度遍历
而我只能想到是递归。虽然图的深度遍历也是利用递归来解答,但是解题思路的高度就低了不少,,而且做题时还忽略了不能查找已经遍历过的元素,这一点很关键地点名了图的特性。
在 code ganker 大神的带领下终于找到解决方案。这实际上就是除了边界上的节点,每个节点都有 4 条边这样一个图,然后对其深度遍历,查找指定的字符串。
大神参考链接:/article/1378240.html
特别注意:对于每一道题,首先要知道它的考点,再具体化算法,再动手写代码,否则写半天也写不对!!!
代码实现:
题目:
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.
解题思路:
这道题考点在图的深度遍历
而我只能想到是递归。虽然图的深度遍历也是利用递归来解答,但是解题思路的高度就低了不少,,而且做题时还忽略了不能查找已经遍历过的元素,这一点很关键地点名了图的特性。
在 code ganker 大神的带领下终于找到解决方案。这实际上就是除了边界上的节点,每个节点都有 4 条边这样一个图,然后对其深度遍历,查找指定的字符串。
大神参考链接:/article/1378240.html
特别注意:对于每一道题,首先要知道它的考点,再具体化算法,再动手写代码,否则写半天也写不对!!!
代码实现:
public class Solution { public boolean exist(char[][] board, String word) { if(word == null || word.length() == 0) return true; if(board == null || board.length == 0 || board[0].length == 0) return false; boolean[][] used = new boolean[board.length][board[0].length]; for(int i = 0; i < board.length; i ++) { for(int j = 0; j < board[0].length; j ++) { if(search(board, word, 0, i, j, used)) return true; } } return false; } boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used) { if(index == word.length()) return true; if(i < 0 || i > board.length - 1 || j < 0 || j > board[0].length - 1 || used[i][j] || word.charAt(index) != board[i][j]) return false; used[i][j] = true; boolean res = search(board, word, index + 1, i - 1, j, used) || search(board, word, index + 1, i + 1, j, used) || search(board, word, index + 1, i, j - 1, used) || search(board, word, index + 1, i, j + 1, used); used[i][j] = false; return res; } }
83 / 83 test cases passed. Status: Accepted Runtime: 11 ms
相关文章推荐
- Hadoop2.x下安装HBase
- 私有构造函数
- opencv MFC 错误解决办法
- 2015-10-28
- 蓝懿iOS 技术内容和心得 10。28技术内容交流和心得分享
- android按钮动画的实现
- 小米开源文件管理器MiCodeFileExplorer-源码研究(5)-AsyncTask异步任务
- 小米开源文件管理器MiCodeFileExplorer-源码研究(5)-AsyncTask异步任务
- 小米开源文件管理器MiCodeFileExplorer-源码研究(5)-AsyncTask异步任务
- 显式调用构造函数和析构函数
- 自定义View实现支付宝芝麻信用页面功能
- Mybatis基本配置和搭建
- 《需求工程-软件建模与分析》读书笔记3
- 字体图标 iconfont cssfont
- 归算法及经典递归例子代码实现
- NOI2015酱油记
- 一些关于style和attr的使用问题
- 二线蓝筹股
- HDOJ 1166 敌兵布阵 (树状数组 & 线段树)
- Oracle函数之非常实用的统计查询