voiddfs(int x, int y, int p){ if (status == true) return; if (p == s.size() - 1 && a[x][y] == s[p]) { status = true; return; } if (a[x][y] != s[p]) { return; } for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (!(nx >= 0 && nx <= n - 1 && ny >= 0 && ny <= m - 1) || vis[nx][ny]) { continue; } vis[nx][ny] = 1; dfs(nx, ny, p + 1); vis[nx][ny] = 0; } }
boolexist(vector<vector<char>>& board, string word){ n = board.size(); m = board.at(0).size(); a = board; s = word; vis.resize(n); for (auto &v: vis) v.resize(m); status = false; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { vis[i][j] = 1; dfs(i, j, 0); vis[i][j] = 0; if (status == true) { returntrue; } } } returnfalse; } };