範例程式碼 uva10336
//uva10336
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void dfs(const vector<string>& world, vector<vector<bool>>& ifvisited,
const int& i, const int& j);
int main() {
int N = 0;
cin >> N;
for (int i = 0; i < N; i++) { // N case
int H = 0, W = 0, max = -1;
vector<int> count(26, 0);
vector<string> world;
vector<vector<bool>> ifvisited;
cin >> H >> W;
world.push_back(string(W + 2, ' '));
for (int j = 0; j < H; j++) {
string input;
cin >> input;
world.push_back(' ' + input + ' ');
}
world.push_back(string(W + 2, ' '));
ifvisited.assign(H + 2, vector<bool>(W + 2, false));
// for (auto j : world) cout << j << endl;
for (int j = 1; j <= H; j++) {
for (int k = 1; k <= W; k++) {
if (!ifvisited[j][k]) {
if (max < ++count[world[j][k] - 'a'])
max = count[world[j][k] - 'a'];
dfs(world, ifvisited, j, k);
}
}
}
cout << "World #" << i + 1 << endl;
for (int j = max; j >= 1; j--) {
for (int k = 0; k < 26; k++) {
if (count[k] == j) {
cout << static_cast<char>(k + 'a') << ": " << count[k]
<< endl;
}
}
}
}
return 0;
}
void dfs(const vector<string>& world, vector<vector<bool>>& ifvisited,
const int& i, const int& j) {
ifvisited[i][j] = true;
if (world[i + 1][j] == world[i][j] && !ifvisited[i + 1][j]) {
dfs(world, ifvisited, i + 1, j);
}
if (world[i][j + 1] == world[i][j] && !ifvisited[i][j + 1]) {
dfs(world, ifvisited, i, j + 1);
}
if (world[i - 1][j] == world[i][j] && !ifvisited[i - 1][j]) {
dfs(world, ifvisited, i - 1, j);
}
if (world[i][j - 1] == world[i][j] && !ifvisited[i][j - 1]) {
dfs(world, ifvisited, i, j - 1);
}
}