原题链接:https://leetcode.com/problems/word-search/
class Solution { public: int n, m; vector<vector<char>> board; vector<vector<int>> visited; string word; bool exist(vector<vector<char>>& _board, string _word) { board = _board; word = _word; m = board.size(), n = board[0].size(); visited = vector<vector<int>> (m, vector<int>(n, 0)); for (int i = 0; i < m; i ++ ) { for (int j = 0; j < n; j ++ ) { if (board[i][j] == word[0]) { if (dfs(1, i, j)) { return true; } } } } return false; } bool dfs(int index, int r, int c) { if (index == word.size()) return true; visited[r][c] = 1; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; for (int i = 0; i < 4; i ++ ) { if (r + dx[i] >= 0 && r + dx[i] < m && c + dy[i] >= 0 && c + dy[i] < n && visited[r + dx[i]][c + dy[i]] != 1 && board[r + dx[i]][c + dy[i]] == word[index]) { if (dfs(index+1, r + dx[i], c + dy[i])) { return true; } } } visited[r][c] = 0; return false; } };