# POJ-1979(BFS)
題目鏈接:http://poj.org/problem?id=1979;
Red and Black
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 44311 Accepted: 24002
Description
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
‘.’ - a black tile
‘#’ - a red tile
‘@’ - a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
6 9
…#.
…#
…
…
…
…
…
#@…#
.#…#.
11 9
.#…
.#.#######.
.#.#…#.
.#.#.###.#.
.#.#…@#.#.
.#.#####.#.
.#…#.
.#########.
…
11 6
…#…#…#…
…#…#…#…
…#…#…###
…#…#…#@.
…#…#…#…
…#…#…#…
7 7
…#.#…
…#.#…
###.###
…@…
###.###
…#.#…
…#.#…
0 0
Sample Output
45
59
6
13
題意理解:典型的BFS板子題,因為自己對BFS的題不是很熟練,所以特意找了這道題來練手。題目大概意思就是與@相連通的" . "有多少個,只能走4個方向。被#隔斷的不算 。最后要注意@也算一個。把最終結果加一。解題思路很簡單,用BFS的板子往上面套就可以了。那就說說自己從這道題里悟出的東西。講講BFS的思路。
我們需要一個隊列,從起點開始將起點放入隊列中,然后進入一個循環,將隊列中的起點取出來看他是否有子節點。
如果有又將節點放隊列里,把自己pop掉
對二三節點依然重復上面的操作。直到隊列為空,或者找到要找的數就終止。這道題里就是將節點換成了四個方向,大體思路沒變。
AC代碼:
#include<cstdio> #include<queue> #include<cstring> using namespace std; int Move[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; char str[25][25]; int vis[25][25]; int n, m, num; struct node{int x, y; }; void bfs(int a, int b) {//printf("%d %d??\n", a, b);queue <node> q;node s, e;s.x = a;s.y = b;q.push(s);while(!q.empty()){s = q.front();q.pop();int x = s.x;int y = s.y;for(int i = 0; i < 4; ++i){x = s.x + Move[i][0];y = s.y + Move[i][1];// printf("%d %d\n", Move[i][0], Move[i][1]);if(x >= 0 && x < m && y >= 0 && y < n && str[x][y] == '.' && !vis[x][y]){//printf("%d %d %d\n", x, y, num);num++;e.x = x;e.y = y;vis[x][y] = 1;q.push(e);}}}} int main() {while(scanf("%d%d", &n, &m), n, m){memset(vis, 0, sizeof(vis));num = 0;for(int i = 0; i < m; ++i)scanf("%s", str[i]);for(int i = 0; i < m; ++i)for(int j = 0; j < n; ++j){if(str[i][j] == '@'){bfs(i, j);}}printf("%d\n", num + 1);}return 0; }總結
以上是生活随笔為你收集整理的# POJ-1979(BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu3951-(Coin Game)
- 下一篇: HDU1159(dp最长公共子序列)