字符迷阵
字符迷陣是一種經典的智力游戲。玩家需要在給定的矩形的字符迷陣中尋找特定的單詞。
在這題的規則中,單詞是如下規定的:
1. 在字符迷陣中選取一個字符作為單詞的開頭;
2. 選取右方、下方、或右下45度方向作為單詞的延伸方向;
3. 以開頭的字符,以選定的延伸方向,把連續得到的若干字符拼接在一起,則稱為一個單詞。
?
以圖1為例,如果要在其中尋找單詞"WORD",則綠色框所標示的都是合法的方案,而紅色框所標示的都是不合法的方案。
現在的問題是,給出一個字符迷陣,及一個要尋找的單詞,問能在字符迷陣中找到多少個該單詞的合法方案。注意合法方案是可以重疊的,如圖1所示的字符迷陣,其中單詞"WORD"的合法方案有4種。
?
?
深度優先搜索。注意方向一旦定了就不能改變了。
手快把'==' 寫成了'=',害我debug了半天,氣死我了。
?
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std;int r, c; int dx[] = {1, 0, 1}; int dy[] = {0, 1, 1};bool dfs(vector<string> &G, int y, int x, const string &word, int pos, const int dir) {int ny = y + dy[dir];int nx = x + dx[dir];if (ny >= r || nx >= c)return false;if (word[pos] != G[ny][nx])return false;if (pos >= word.size() - 1)return true;return dfs(G, ny, nx, word, pos + 1, dir); }int main() {int n;cin >> n;while (n--){cin >> r >> c;vector<string> G(r);for (int i = 0; i < r; ++i)cin >> G[i];string word;cin >> word;//vector<vector<bool>> vis(r, vector<bool>(c, false));int ans = 0;for (int i = 0; i < r; ++i){for (int j = 0; j < c; ++j){if (G[i][j] == word[0]){if(dfs(G, i, j, word, 1, 0))++ans;if (dfs(G, i, j, word, 1, 1))++ans;if (dfs(G, i, j, word, 1, 2))++ans;}}}cout << ans << endl;} }總結
- 上一篇: 舌尖上的家乡——广东云浮/罗定
- 下一篇: 【微信小程序】粤语教学平台-粤言粤语