解題心得
我反而不是卡bfs,而是卡再怎麼輸出好久,最開始是用map紀錄,但要依照value輸出好麻煩。
程式碼
#include <iostream> #include <vector> using namespace std; int h, w; void bfs(vector<vector<char>>& map, int x, int y, char c) { map[y][x] = '@'; if (x - 1 >= 0 && map[y][x - 1] == c) bfs(map, x - 1, y, c); if (x + 1 < w && map[y][x + 1] == c) bfs(map, x + 1, y, c); if (y - 1 >= 0 && map[y - 1][x] == c) bfs(map, x, y - 1, c); if (y + 1 < h && map[y + 1][x] == c) bfs(map, x, y + 1, c); } int main() { int n; cin >> n; for (int round = 1; round <= n; round++) { cin >> h >> w; int dict[26] = { 0 }; vector<vector<char>> map(h, vector<char>(w, '@')); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) cin >> map[i][j]; } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (map[i][j] != '@') { dict[map[i][j] - 'a']++; bfs(map, j, i, map[i][j]); } } } cout << "World #" << round << endl; int maxCount = 0; for (int i = 0; i < 26; i++) maxCount = max(maxCount, dict[i]); while (maxCount) { for (int i = 0; i < 26; i++) { if (maxCount == dict[i]) cout << char('a' + i) << ": " << dict[i] << endl; } maxCount--; } } return 0; }
沒有留言:
張貼留言