PekingUniversityOJ No.1979
本文最后更新于:2 年前
这学期一时兴起选修选了个acm课,其实就想补补自己的数据结构和算法,大学前两年下来感觉代码功底不够扎实,希望借此机会巩固加强一下代码能力,算法题我主要以C++来实现,因为自己C++没有系统的学习过,就以练代学吧!
本题是一道很简单的搜索题,也正好是课上刚巩固的内容。这里我使用的是广度优先搜索,单纯因为想练练广搜的算法实现。
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
Source:
Japan 2004 Domestic
1 |
|
总结
很久没有写算法题了,代码自认为写得就不是很好看,其实中间还有很多可以改变的地方。看过别人写的这道题的代码。不使用单独的判重数组,每次访问到队列中的某个节点后将此节点上的内容改为‘#’,也就没法再次访问了,也是很好的想法。不过我还是倾向去将各个模块分割,重复状态的判断我认为还是在搜索算法里是一个很重要的模块。
coding期间出现的问题
忘记初始化判重数组【一开始我也没写bool in函数】,导致在从第二次及以后的瓦片读取后计算可能会出错(遗留下来的map会影响下一张map)。
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!