1. 程式人生 > 實用技巧 >挑戰程式設計競賽 2.1章習題 AOJ 0118 Property Distribution dfs bfs

挑戰程式設計競賽 2.1章習題 AOJ 0118 Property Distribution dfs bfs

地址https://vjudge.net/problem/Aizu-0118

原文是日誌 大概題意是 H*W的果園種滿了蘋果、梨、蜜柑三種果樹,如果把上下左右看成是連線狀態那麼請問果園可以劃分成幾個區域

輸入

多組資料

第一行輸入兩個數值 H W 代表果園的長和寬

然後輸入H行W列的char陣列 代表蘋果、梨、蜜柑(@ # * 表示 )

0 0 表示輸入結束

輸出

每行輸出一個答案 表示果園可以劃分成多少個相同水果區域 


Sample Input
10 10
####*****@
@#@@@@#*#*
@##***@@@*
#****#*@**
##@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##** @****#@@#@ 0 0 Output for the Sample Input 33

解法

DFS BFS 並查集均可

類似

poj 1979 Red and Black 題解《挑戰程式設計競賽》

程式碼如下 可當作dfs模板

// 11235.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始並結束。
//

#include <iostream>

using namespace std;

const int N = 110;

char arr[N][N];

int H, W;
int cnt = 0;
int addx[4] = { 1,-1
,0,0 }; int addy[4] = { 0,0,1,-1 }; void dfs( int x, int y,char p) { arr[x][y] = '0'; for (int i = 0; i < 4; i++) { int newx = x + addx[i]; int newy = y + addy[i]; if (newx >= 0 && newx < H && newy >= 0 && newy < W && arr[newx][newy] == p) { dfs(newx, newy, p); } } }
int main() { while (cin >> H >> W, W != 0) { for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> arr[i][j]; } } cnt = 0; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (arr[i][j] != '0') { cnt++; dfs(i, j, arr[i][j]); } } } cout << cnt << endl; } return 0; }