题意:给定一个n*m的矩阵,然后问你里面存在“girl”和“cat”的数量。
析:很简单么,就是普通搜索DFS,很少量。只要每一个字符对上就好,否则就结束。
代码如下:
#include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> using namespace std ; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 1000 + 5; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; char s[maxn][maxn]; int n, m; int vis[maxn][maxn]; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int dfs(int r, int c, char *t, int x, bool ok){ if(x == 3 && ok){ if(s[r][c] == t[x]) return 1; return 0; } else if(!ok && x == 2){ if(s[r][c] == t[x]) return 1; return 0; } int ans = 0; for(int i = 0; i < 4; ++i){ int xx = r + dr[i]; int yy = c + dc[i]; if(is_in(xx, yy) && s[xx][yy] == t[x+1]) ans += dfs(xx, yy, t, x+1, ok); } return ans; } int main(){ int T; cin >> T; while(T--){ scanf("%d %d", &n, &m); for(int i = 0; i < n; ++i) scanf("%s", s[i]); int ans1 = 0; int ans2 = 0; for(int i = 0; i < n; ++i){ for(int j = 0; j < m; ++j){ if(s[i][j] == 'g'){ ans1 += dfs(i, j, "girl", 0, true); } else if(s[i][j] == 'c') ans2 += dfs(i, j, "cat", 0, false); } } cout << ans1 << " " << ans2 << endl; } return 0; }