企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**一. 题目描述** 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)