hdu-1312 Red and Black

xiaoxiao2021-02-28  122

Red and Black

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 15   Accepted Submission(s) : 14
Problem 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)   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   题目大意:就是给出一个M*N规模的矩阵,@符号为起始位置,以起始位置开始,符号'.'是可以行走的区域, 符号#是不能行走的区域,且在每个地方只向上下左右四个方向行走。题目要求的是从@开始走所能到达的全 部方块, 如第一组测试数据。左下角,右下角。 和右上角的点都是被包围了的,不可能走到那个地方,再加上 有#的地方不能走, 不能到达的地方有9个,总共有6*9, 54个方格,不能到达的有九个,所以有四十五个是可 以到达的,所以第一组测试数据所对应的答案是45. 解题思路: 这道题使用的是广搜广搜都可以做,深搜就相当于油田问题。广搜:即从起始位置开始进行广搜,先让起始位置进队,然后让他出队搜它四周的四个方向, 按照从当前所在位置的正上方开始按逆时针方向搜索, 如果发现这个位置是可以行走的,且这个位置的坐标 没有越界,那么我们将这个位置标记为#,代表这个位置已经走过了,并让这个位置进队,让累加的sum+1,代表 可达到的区域加1,然后循环这个过程,最终结果是所有可到达的区域都会被赋值为#,此时若队列中还有元素, 则会继续循环,队中元素依次出队,当队列为空时,返回 sum的值即为答案。

#include <iostream> #include <string.h> #include <cstdio> #include <queue> using namespace std; int n,m,sum; char a[100][100]; int cx[4][2]={0,1,0,-1,1,0,-1,0}; struct node { int x; int y; }now; void bfs () { sum=0; int i,j; queue<node>q; node next; q.push(now); while (!q.empty()) { now = q.front(); q.pop(); for (i=0;i<4;i++) { next.x = now.x+cx[i][0]; next.y = now.y+cx[i][1]; if (next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&a[next.x][next.y]!='#') { sum++; a[next.x][next.y]='#'; q.push(next); } } } cout<<sum+1<<endl; } int main() { int i,j; while (scanf("%d %d",&m,&n)&&n&&m) { for (i=0;i<n;i++) { for (j=0;j<m;j++) { cin>>a[i][j]; if (a[i][j]=='@') { now.x = i; now.y = j; a[i][j]='#'; } } } bfs(); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-24823.html

最新回复(0)