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;
}

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