【基礎練習】【DFS】codevs2806 紅與黑題解

題目描述 Description

有一個矩形房間,覆蓋正方形瓷磚。每塊瓷磚塗成了紅色或黑色。一名男子站在黑色的瓷磚上,由此出發,可以移到四個相鄰瓷磚之一,但他不能移動到紅磚上,只能移動到黑磚上。編寫一個程序,計算他通過重複上述移動所能經過的黑磚數。

 

輸入描述 Input Description

輸入包含多個數據集。一個數據集開頭行包含兩個正整數W和H,W和H分別表示矩形房間的列數和行數,且都不超過20.
每個數據集有H行,其中每行包含W個字符。每個字符的含義如下所示:
'.'——黑磚
'#'——紅磚
'@'——男子(每個數據集僅出現一次)
兩個0表示輸入結束。

輸出描述 Output Description

對每個數據集,程序應該輸出一行,包含男子從初始瓷磚出發可到達的瓷磚數。

樣例輸入 Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0

樣例輸出 Sample Output

45
59
6
13

裸題 暴搜可過

注意每次數組清空 注意字符讀入

//codevs2806 ºìÓëºÚ DFS
//½ñÌìÍíÉϾëÁË Ð´ËÑË÷°É дÉÏÈýµÀ È»ºó¿´¿´ÎÄ»¯¿Î
//copyright by ametake
#include
#include
using namespace std;

const int maxn=20+5;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
bool a[maxn][maxn],vis[maxn][maxn];//1ºÚ
int w,h,ans=0;

bool can(int xx,int yy)
{
	if (xx<1||xx>h||yy<1||yy>w||!a[xx][yy]||vis[xx][yy]) return false;
	return true;
}

void dfs(int xx,int yy)
{
	vis[xx][yy]=true;
	ans++;
	for (int i=0;i<4;i++)
	{
		xx+=dx[i];
		yy+=dy[i];
		if (can(xx,yy)) dfs(xx,yy);
		xx-=dx[i];
		yy-=dy[i];
    }
    return;
}

int main()
{
	freopen("1.txt","r",stdin);
	char ch;
	int xx,yy;
	while(scanf("%d%d",&w,&h)==2&&w)
	{
		ans=0;
		memset(a,0,sizeof(a));
		memset(vis,0,sizeof(vis));
		scanf("%c",&ch);
		for (int i=1;i<=h;i++)
		{
			for (int j=1;j<=w;j++)
			{
				scanf("%c",&ch);
				if (ch=='.') a[i][j]=1;
				else if (ch=='@')
				{
					xx=i;
					yy=j;
			    }
		    }
		    scanf("%c",&ch);
	    }
	    dfs(xx,yy);
	    printf("%d\n",ans);
    }
    return 0;
}

——塵世難逢開口笑,菊花須插滿頭歸



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