CodeForces 6B-President‘s Office(简单的DFS)

题目描述:

President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.

The office-room plan can be viewed as a matrix with n n n rows and m m m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

输入:

The first line contains two separated by a space integer numbers n n n , m m m ( 1<=n,m<=100 1<=n,m<=100 1<=n,m<=100 ) — the length and the width of the office-room, and c c c character — the President's desk colour. The following n n n lines contain m m m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters. 

输出: 

Print the only number — the amount of President's deputies. 

样例输入:(有两组)

3 4 R

G.B.

.RR.

TTT.  

3 3 Z

...

.H.

..Z

样例输出: 

2

题目大意 and 解题思路:

第一行:房间长n,宽m,总统办公桌代表的字符。

接下来2 ~ n+1行,每行输入m列:房间内的办公桌的颜色(大写字母)。"."为空单元格。

求出在总统桌四周相邻的办公桌数量。

对于样例1:总统桌子为R,而周围与其相连的有上方的B,和下方的三个T,所以数量为2,即样例1的输出为2。

这道题其实就是DFS,首先找到总统桌子对应字符在地图中的位置,然后四个方向遍历搜索,对于与其相连的桌子,用一个标记数组进行标记,在这里,相同的字母只算一个数量(例如:样例中的三个T其实算一个),所以只需要定义一个一维标记数组,将每种桌子的字符转换成对应的ASCII码进行标记就可以了,最后得到多少种不同的标记,结果就是多少!

AC Code: 

#include<bits/stdc++.h>
using namespace std;
const int N=101;
char s[N][N];//存入地图的数组 
char p;//总统的桌子 
int n,m,ans;
int vis[N];//标记其他的桌子,因为桌子均为26个英文字母,相同的字母算同一类,这里定义为一维数组就可以了 
int dx[]={0,0,1,-1};//这两个是方向数组 
int dy[]={1,-1,0,0};
void dfs(int x,int y) {
	for(int k=0;k<4;k++) {//四个方向进行搜索 
		int tx=x+dx[k];
		int ty=y+dy[k];
		if(tx<0||tx>=n||ty<0||ty>=m)//越界判断 
			continue;
		if(s[tx][ty]!='.') {//如果不是单元格,即为桌子 
			if(s[tx][ty]!=p) {//如果不是总统桌子 
				vis[s[tx][ty]-'A'+1]=1;//对此桌子进行标记,下标为字母对应的ASCII码 
				s[tx][ty]='.';//访问过此桌子,将其修改为单元格 
			}else {//如果是总统桌子 
				s[tx][ty]='.';//将其修改为单元格 
				dfs(tx,ty);//从总统桌子的某个点继续搜索 
			}
		}
	}
}
int main() {
	memset(vis,0,sizeof(vis));//标记数组清零 
	scanf("%d %d %c",&n,&m,&p);
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
			scanf(" %c",&s[i][j]);//%前面的空格确保完整输入 
	for(int i=0;i<n;i++) {
		for(int j=0;j<m;j++) {
			if(s[i][j]==p) {//从总统桌子的这个点开始搜索 
				dfs(i,j);
			}
		}
	}
	for(int i=1;i<=26;i++)
		if(vis[i])//同一个字母形成一类桌子,数量加1 
			ans++;
	printf("%d\n",ans);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章