## BFS & DFS

BFS & DFS

##打卡第 2^2 天
一、区别
DFS实际上就是实现类似于一个的操作,会用到递归,将节点按照深度优先的次序压栈,后面再以相反的次序出栈进行新的检测。通俗讲就是一直走到底,若无路可走就返回到最近的那个分岔口,而且这个分岔口还有没探索过的分岔路。多深都往里走,不管数据层数,路不通返回就是了。

BFS实际上就是实现一个队列的操作,会用到queue,将本节点处理完毕之后,再将周围相邻的节点入列,即现处理同一层的数据(走一步就能取到的数据),一层一层走遍所有数据。

二、BFS
用一个队列来记录数据,同一层的数据紧挨在一起,逐渐一个一个读取,来寻找符合条件的相邻的数据(因为只能走一步)放入队列中,队列中可能有不同层的数据,但同一层的会按顺序挨在一起。读一个放入队尾,踢一个队头,将所有数据遍历完。
A while ago I had trouble sleeping. I used to lie awake, staring at the ceiling, for hours and hours. Then one day my grandmother suggested I tried counting sheep after I’d gone to bed. As always when my grandmother suggests things, I decided to try it out. The only problem was, there were no sheep around to be counted when I went to bed.

Creative as I am, that wasn’t going to stop me. I sat down and wrote a computer program that made a grid of characters, where # represents a sheep, while . is grass (or whatever you like, just not sheep). To make the counting a little more interesting, I also decided I wanted to count flocks of sheep instead of single sheep. Two sheep are in the same flock if they share a common side (up, down, right or left). Also, if sheep A is in the same flock as sheep B, and sheep B is in the same flock as sheep C, then sheeps A and C are in the same flock.

Now, I’ve got a new problem. Though counting these sheep actually helps me fall asleep, I find that it is extremely boring. To solve this, I’ve decided I need another computer program that does the counting for me. Then I’ll be able to just start both these programs before I go to bed, and I’ll sleep tight until the morning without any disturbances. I need you to write this program for me.

Input
The first line of input contains a single number T, the number of test cases to follow.

Each test case begins with a line containing two numbers, H and W, the height and width of the sheep grid. Then follows H lines, each containing W characters (either # or .), describing that part of the grid.

Output
For each test case, output a line containing a single number, the amount of sheep flock son that grid according to the rules stated in the problem description.

Notes and Constraints
0 < T <= 100
0 < H,W <= 100

Sample Input
2
4 4
#.#.
.#.#
#.##
.#.#
3 5
###.#
…#…
#.###

Sample Output
6
3
在这里插入图片描述
三、DFS
用一组visted[ ]数据记录每个岔口(节点)的分岔路(边)数,只要有岔路没有探索过,就进入。无路可走就返回最近的而且有还没探索过的岔路的分岔口,接着探索它的这条分岔路。探索过的路若通向死胡同,岔口的visted就减1。直到不管多深,有路就走,不行就退,直到到达目标节点。

猜你喜欢

转载自blog.csdn.net/Delta_laibuji/article/details/113059019