ACM-AK吧!少年
AK is an ACM competition finished all of the problems. AC This problem is one of the steps,so fight to AK。There are a number of graphics"_" and "#",In the graph,"#"make up "A" or "K" these two letters。Makea program to identify these letters, we want to kown the number of these twoletters.
輸入
Input contains multiple test cases.
Each test case contains two integer N (10<=N<=100) and M (10<=M<=100) is the graphics of the number of rows and columns。
Next graphics, letter fonts and titles to describe these two letters the same standard fonts, letter size is not necessarily the same, and does not skew, each letter occupies a separate rectangular area itself is connected, do not cross, and other letters or connected.
輸出
Each test case output the number of "A" and "K".
樣例輸入
10 47 _______________________________________________ _____________####________#####______###________ ____________#######_______####_____###_________ ___________###__###________###___#####_________ ________#####____###_______###_###_____________ _________###______###______######______________ ________##############_____###_###_____________ _______###__________###____###___###___________ ______#####________####___###_____###__________ _____###______________###__###_______###_______
樣例輸出
1 1
思路:DFS判斷圖形即可。
#include "stdafx.h" //AK吧,少年! //解題思路: //1.深搜或者廣搜遍歷 //2.遇到第一個合適的節點檢查是“A”還是“K”,A和K的區別是x+1,y-1是不是# //因為是一次遍歷就遍歷完全所有相連節點,所以只要判斷符合條件的節點的特殊位置就可以判斷是哪個字母 #include <stdio.h> #include <string.h> const int MAX = 105; int vis[MAX][MAX]; char map[MAX][MAX]; int dir[8][2] = { 0, 1, 0, -1, 1, 0, -1, 0, -1, -1, -1, 1, 1, -1, 1, 1 }; int n, m,ans[2]; void DFS(int x, int y) { vis[x][y] = 1; for (int i = 0; i < 8; i++) { int nx = dir[i][0] + x; int ny = dir[i][1] + y; if (nx >= 0 && ny >= 0 && nx < n && ny < m && !vis[nx][ny] && map[nx][ny] == ‘#‘) { DFS(nx, ny); } } } #include <iostream> #include <queue> using namespace std; struct Point { int x, y; }; queue<Point> q; void BFS(int x, int y) { vis[x][y] = 1; Point p; p.x = x; p.y = y; q.push(p); while (!q.empty()) { Point p = q.front(); q.pop(); int x = p.x; int y = p.y; vis[x][y] = 1; for (int i = 0; i < n; i++) { int nx = dir[i][0] + x; int ny = dir[i][1] + y; if (nx >= 0 && ny >= 0 && nx < n && ny < m && !vis[nx][ny] && map[nx][ny] == ‘#‘) { Point p; p.x = nx; p.y = ny; q.push(p); } } } } int check(int x, int y) { if (map[x + 1][y - 1] == ‘#‘) return 0; else return 1; } int main() { while (scanf("%d %d", &n, &m) != EOF) { memset(vis, 0, sizeof(vis)); memset(ans, 0, sizeof(ans)); for (int i = 0; i < n; i++) { scanf("%s", map[i]); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!vis[i][j] && map[i][j] == ‘#‘) { //DFS(i, j); BFS(i, j); ans[check(i, j)] ++; } } } printf("%d %d\n", ans[0], ans[1]); } return 0; }
ACM-AK吧!少年