華爲機試之笨笨熊搬家

森林裏的苯苯熊要喬遷新喜,上次他已經將物品打包完成,並約了朋友來幫忙。接下來他要選定一個搬家的時間,想了很久,就決定在國慶節進行,因爲國慶放假朋友們都有時間啦。但是在森林裏,從他現在房子到新豪宅,所經之地有山有水,路途曲折,甚至有些道路是不通的。
請你和他一起查看指定的地圖,看看從笨笨熊現在的房子到新宅之間,道路是否是暢通的呢?
地圖是R行、C列的矩陣,矩陣的每一個格子剛好是一天的行程。
矩陣由“B”、“-”、“#”、“H”四種字符成員組成,其中:
B: 代表苯苯熊現在的房子;
H: 代表笨笨熊新的豪宅;
-: 代表可以通行的道路;
#: 代表無法通過的障礙(高山、大河等);
此外,森林裏也有交通規則地:在任務位置,只能向“上、下、左、右”四個方向中的其中一個方向行走。
輸入:
4 // R的數值
7 // C的數值,下面是地圖。
--##---
B-----H
#---#--
-------
輸出:
Y //代表道路可達

N //代表道路不通
樣例輸入:
1
5
-B-H#
樣例輸出:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
struct MAP_tree
{
	char name;
	int size;
	MAP_tree *up;
	MAP_tree *down;
	MAP_tree *left;
	MAP_tree *right;
};
string res = "N";
void upOrder(MAP_tree *map)
{
	if(map->size == 1 && map->name != '#')
	{
		map->size=0;
		if(map->name == 'H')
		{
			res = "Y";
		}
		if((map->up)!= NULL)
		    upOrder(map->up);
		if((map->right) != NULL)
			upOrder(map->right);
		if(map->down != NULL)
			upOrder(map->down);
		if(map->left != NULL)
			upOrder(map->left);
	}
}
int main()
{
	int old_r = 0,old_c = 0;
	int R;//行數
	int C;//列數
	int i=0,j=0;
	while(cin>>R>>C)
	{
		res = "N";
		MAP_tree map[50][50];
		for(i = 0;i<50;i++)
			for(j = 0;j<50;j++)
			{
				map[i][j].down = NULL;
				map[i][j].left = NULL;
				map[i][j].right = NULL;
				map[i][j].up = NULL;
				map[i][j].size = 1;
			}
		string cnt[50];
		for(i = 0;i<R;i++)
			cin>>cnt[i];
		for(i = 0;i<R;i++)
			for(j = 0;j<C;j++)
			{
				map[i][j].name = cnt[i][j];
				if(cnt[i][j] == 'B')
				{
					old_r = i;
					old_c = j;
				}
				if((i+1)<R)
					map[i][j].down = &map[i+1][j];
				if((j+1)<C)
					map[i][j].right = &map[i][j+1];
				if(i!= 0)
					map[i][j].up = &map[i-1][j];
				if(j != 0)
					map[i][j].left = &map[i][j-1];
			}
			upOrder(&map[old_r][old_c]);
			cout<<res<<endl;
			//cin>>i;
			
	}
	system("pause");
	return 0;
}


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