(step4.2.2)hdu 1312(Red and Black——BFS)

来源:互联网 发布:黑马程序员有用吗 编辑:程序博客网 时间:2024/05/17 01:52

题目大意:给一个w*h的黑白棋盘,一个人站在某个黑色点上,并且这个人只能访问和他相邻的

*黑色点,求这个人能一共能访问多少个点


解题思路:BFS

1)scanf(" %c",&map[i][j]);。%c前面的空格用于去除一个字符前面的空白(包括回车、空格。。。)

.这是要特别注意的


代码如下:

/* * 1312_2.cpp * *  Created on: 2013年8月15日 *      Author: Administrator *      加油。。。我的女神是章泽天。。。。 */#include <iostream>#include <queue>using namespace std;/** * 用sx、sy来保存起始点的坐标 * n: 行数 * m: 列数 * */int sx,sy,n,m;//用来保存输入的字符char map[21][21];const int maxn = 100;bool visited[maxn][maxn];//用来标记是否访问过int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//点的移动方向struct State{int x ;//(x,y)用于表示第x行第y列int y;int step_counter;};bool checkState(State st){//!!一定要将这里的x,y与坐标系上的x,y区分开if((!visited[st.x][st.y])&&(map[st.x][st.y] == '.')&&(st.x >= 1 && st.x <= n && st.y >= 1 && st.y <= m)){return true;}return false;}void bfs(){queue<State> q;State st,now,next;st.x = sx;st.y = sy;int num = 0;q.push(st);memset(visited,0,sizeof(visited));visited[st.x][st.y] = 1;while(!q.empty()){num++;now = q.front();int i;for( i = 0 ; i < 4 ; ++i){next.x = now.x + dir[i][0];next.y = now.y + dir[i][1];if(checkState(next)){q.push(next);visited[next.x][next.y] = 1;}}q.pop();}printf("%d\n",num);}int main(){while(scanf("%d%d",&m,&n)!=EOF,n||m){int i,j;for(i = 1; i <= n ; ++i){for( j = 1 ; j <= m ; ++j){scanf(" %c",&map[i][j]);//这里的%c前面一定要有一个空格,用于去除一个字符前面的所有空格。否则会出错。。。。if(map[i][j] == '@'){sx = i;sy = j;}}}bfs();}}




原创粉丝点击