BIT1038 Red and Black

之前在hduAC的代码由于年代过于久远已经找不到了。。。。重写。。

这题应该是BFS入门题,用BFS跑一下就过了

题意:

有多组样例,每组样例的第一行是矩阵的宽和高

接下来是个字符矩阵

.表示可走,#表示不可走,@为起点

求矩阵中人可以到达的地方的数目,人只能上下左右移动

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
char board[30][30];//board[H-1][W-1]
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
class coordinate
{
public:
	int x,y;
};
int W,H;
bool inBoard(coordinate a)
{
	return a.x>=0&&a.x<H&&a.y>=0&&a.y<W;
}
int main()
{
	while(cin>>W>>H,W||H)
	{
		coordinate start;//起点
		for(int i=0;i<H;i++)
		{
			for(int j=0;j<W;j++)
			{
				cin>>board[i][j];
				if(board[i][j]=='@')
				{
					start.x=i;
					start.y=j;
				}
			}
		}
		queue<coordinate>Q;
		Q.push(start);
		board[start.x][start.y]='#';
		int counter=0;
		while(!Q.empty())
		{
			coordinate temp=Q.front();Q.pop();
			counter++;
			for(int i=0;i<4;i++)
			{
				coordinate patch;
				patch.x=temp.x+dir[i][0];
				patch.y=temp.y+dir[i][1];
				if(!inBoard(patch))
				{
					continue;
				}
				if(board[patch.x][patch.y]=='#')
				{
					continue;
				}
				Q.push(patch);
				board[patch.x][patch.y]='#';
			}
		}
		printf("%d\n",counter);
	}
	return 0;
}


你可能感兴趣的:(BIT1038 Red and Black)