Leetcode之Word Search 问题
2017-09-24 21:04
260 查看
问题描述:
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 =
word =
word =
问题来源:Word Search (详细地址:https://leetcode.com/problems/word-search/description/)
思路分析:这道题很明显是一个递归问题,需要判断“上下左右”四个方位的情况才能找到答案,只要这四个方位中找到一个的话我们就能得出正确结果了,相反如果四个方位都没有的话,那么返回的结果就是false了。递归问题主要是找到递归出口和递归条件,递归条件应该是很简单的,只要四个方位求或关系就行了,返回一个布尔值作为结果。
下面找找递归出口以及边界(row表示行的索引,col表示列的索引):
第一个边界:if(row < 0 || col < 0 || row == board.length || col == board[0].length)肯定是false;
第二个边界:if(board[row][col] != word.charAt(index))对应的字符对不上,肯定也是返回false;
第三个边界(也是出口):index == word.length()递归的索引到达了给定字符串的末尾了,也就是说word中的所有字符都匹配了,返回的当然是true了。
代码:
主体部分:
递归部分:
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.
问题来源:Word Search (详细地址:https://leetcode.com/problems/word-search/description/)
思路分析:这道题很明显是一个递归问题,需要判断“上下左右”四个方位的情况才能找到答案,只要这四个方位中找到一个的话我们就能得出正确结果了,相反如果四个方位都没有的话,那么返回的结果就是false了。递归问题主要是找到递归出口和递归条件,递归条件应该是很简单的,只要四个方位求或关系就行了,返回一个布尔值作为结果。
下面找找递归出口以及边界(row表示行的索引,col表示列的索引):
第一个边界:if(row < 0 || col < 0 || row == board.length || col == board[0].length)肯定是false;
第二个边界:if(board[row][col] != word.charAt(index))对应的字符对不上,肯定也是返回false;
第三个边界(也是出口):index == word.length()递归的索引到达了给定字符串的末尾了,也就是说word中的所有字符都匹配了,返回的当然是true了。
代码:
主体部分:
递归部分:
相关文章推荐
- LeetCode--word Search问题
- leetcode -- 516. Longest Palindromic Subsequence【角度,问题的递推表示,数据结构】
- leetcode:括号匹配问题
- [LeetCode] Climbing stairs 爬楼梯问题
- LeetCode 2. Add Two Numbers 链表加和问题
- 【LeetCode111-120】很多道二叉树的问题(左右顺序很重要),一道hard DP题,两道杨辉三角以及一道DP三角
- LeetCode:Word Search
- [Leetcode] word search 单词查询
- Leetcode中的回溯法题目总结:八皇后问题; unique path问题;subsets问题
- LeetCode-TwoSum问题
- Leetcode全游戏问题
- LeetCode二叉树遍历的问题
- leetcode问题解答:23. Merge k Sorted Lists
- leetcode 462. Minimum Moves to Equal Array Elements II 换一个角度思考问题 + 寻找中位数
- LeetCode 79. Word Search
- [LeetCode] N-Queens N皇后问题
- leetcode 79. Word Search
- Leetcode之Palindrome Linked List 问题
- Leetcode之Minimum Size Subarray Sum 问题
- leetcode围棋问题