leetcode_079 Word Search
2016-04-07 22:41
357 查看
题目分析:
给定一个二维的字母板,可以在字母板上演着四个方向(上、下、左、右)走,来查找一个给定的单词是否存在。注意同一个位置只能走一次,即不能重复。
解题思路:
深度优先搜索实现
利用DFS对一个起点字母进行上、下、左、右搜索,判断是否是给定的word。因为同一个位置只能走一次,故使用一个visited数目来记录当前的字母是否已经被访问过,访问完这一次搜索后,在将其对应的visited置为false,因为对于下一次的访问,当前元素应该是可以被访问的。
实现程序
给定一个二维的字母板,可以在字母板上演着四个方向(上、下、左、右)走,来查找一个给定的单词是否存在。注意同一个位置只能走一次,即不能重复。
解题思路:
深度优先搜索实现
利用DFS对一个起点字母进行上、下、左、右搜索,判断是否是给定的word。因为同一个位置只能走一次,故使用一个visited数目来记录当前的字母是否已经被访问过,访问完这一次搜索后,在将其对应的visited置为false,因为对于下一次的访问,当前元素应该是可以被访问的。
实现程序
class Solution { public: // dfs辅助函数 bool dfs(vector< vector<char> > &board, string &word, int index, int x, int y, vector< vector<bool> > &visited) { // 满足单词长度,返回true if (index == word.size()) return true; // 超越字母板的边界,则返回falase if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false; // 已访问过,则提前结束此次访问,返回false if (visited[x][y]) return false; // 不是当前字母,则结束此次访问,返回false if (board[x][y] != word[index]) return false; // 置当前访问位置为已访问 visited[x][y] = true; // 递归向四个方向进行查找判断 bool ret = dfs(board, word, index + 1, x - 1, y, visited) || //上 dfs(board, word, index + 1, x + 1, y, visited) || //下 dfs(board, word, index + 1, x, y - 1, visited) || //左 dfs(board, word, index + 1, x, y + 1, visited); //右 // 返回到原来未被访问的位置 visited[x][y] = false; return ret; } bool exist(vector< vector<char> > &board, string word) { int m = board.size(); int n = board[0].size(); // 创建visited数组,用来标识字母盘位置是否被访问 vector< vector<bool> > visited(m, vector<bool> (n, false)); // 控制访问的起始行位置 for (int i = 0; i < m; i++) { // 控制访问的起始列位置 for (int j = 0; j < n; j++) { // 从起始位置开始深度搜索遍历查找 if (dfs(board, word, 0, i, j, visited)) return true; } } return false; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解