**一. 题目描述**
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 neighbouring. The same letter cell may not be used more than once.
For example, Given board =
~~~
[
["ABCE"],
["SFCS"],
["ADEE"]
]
~~~
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
**二. 题目分析**
题目的大意是,给定一个board字符矩阵和一个word字符串,可以从矩阵中任意一点开始经过上下左右的方式走,每个点只能走一次,若存在一条连续的路径,路径上的字符等于给定的word字符串的组合,则返回true,否则返回false。
解决的方法类似于走迷宫,使用递归回溯即可。由于走过的路径需要排除,因此构造一个辅助数组记录走过的位置,防止同一个位置被使用多次。
**三. 示例代码**
~~~
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:
bool exist(vector<vector<char> > &board, string word)
{
const int x = board.size();
const int y = board[0].size();
// 用于记录走过的路径
vector<vector<bool> > way(x, vector<bool>(y, false));
for (int i = 0; i < x; ++i)
{
for (int j = 0; j < y; ++j)
{
if (dfs(board, way, word, 0, i, j))
return true;
}
}
return false;
}
private:
bool dfs(vector<vector<char> > &board, vector<vector<bool> > way, string word, int index, int x, int y)
{
if (index == word.size()) // 单词完成匹配
return true;
if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size()) // 超出边界
return false;
if (word[index] != board[x][y]) // 遇到不匹配
return false;
if (way[x][y]) // 该格已经走过,返回false
return false;
// 若该格未曾走过,可进行递归
way[x][y] = true;
bool result = dfs(board, way, word, index + 1, x + 1, y) || // 往上扫描
dfs(board, way, word, index + 1, x - 1, y) || // 往下扫描
dfs(board, way, word, index + 1, x, y + 1) || // 往右扫描
dfs(board, way, word, index + 1, x, y - 1); // 往左扫描
way[x][y] = false;
return result;
}
};
~~~
![](https://box.kancloud.cn/2016-01-05_568bb5f166794.jpg)
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016腾讯软件开发笔试题)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契数列问题)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波兰式的计算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和问题)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching