Vous êtes sur la page 1sur 10

Floodfill Algorithm

A floodfill is a name given to the following basic idea: In a space (typically 2-D or 3-D) with a initial starting s !are" fill in all the areas ad#acent to that space with some val!e or item" !ntil some bo!ndary is hit$ As an e%ample" imagine an inp!t 2-D array that shows the bo!ndary of a la&e (land is designated with ' characters$) ********** ** *** * * * * * * * * * * * * ********** (ow" imagine that yo! wanted to fill in a )la&e* with the + character$ ,e-d li&e to write a f!nction that ta&es in one spot in the la&e (the coordinates to that spot in the grid)" and fills in each contig!o!s empty location with the + character$ .!r final grid sho!ld loo& li&e: ********** **~~***~~* *~~~~*~~~* *~~~~*~~~* *~~~~~~~~* *~~~~*~~~* **********

.f co!rse" in this partic!lar" e%ample" we co!ld #!st fill in all spaces with + characters" b!t it-s easy to imagine a larger grid where we #!st fill in this one la&e and not other areas with spaces$ Depending on how the floodfill sho!ld occ!r (do we #!st fill in each s !are above" below" left and right" or do we A/0. fill in diagonals to s !ares already filled)" the basic idea behind a rec!rsive f!nction that carries o!t this tas& is as follows (this is #!st a very ro!gh s&etch in pse!docode: void FloodFill(char grid[][SIZE], int x, int y) { grid[x][y] = FILL_ !"#" $E#% &or ('ach ad(ac'nt location i,( to x,y) { i& (i,( i) in*o+nd) and not &ill'd) FloodFill(grid, i, ()% , ,hen we act!ally write code for a floodfill" we may either choose to !se a loop to go thro!gh all ad#acent locations" or simply spell o!t the locations" one by one$ If there are 1 locations" a loop is !s!ally desirable$ If there are 2 or fewer" it might #!st ma&e sense to write each rec!rsive call o!t separately$

3inesweeper - 4ec!rsive 5lear


3inesweeper is the pop!lar game incl!ded with ,indows where the player has to determine the location of hidden bombs in a rectang!lar grid$ Initially" each s !are on the grid is covered$ ,hen yo! !ncover a s !are" one of three things can happen: 6) A bomb is at that s !are and yo! blow !p and lose$ 2) A n!mber appears" signifying the n!mber of bombs in the ad#acent s !ares$ 3) 7he s !are is empty" signifying that there are no ad#acent bombs$ In the real minesweeper" when step 3 occ!rs" all of the ad#acent s !ares are a!tomatically cleared for yo!" since it8s obvio!sly safe to do so$ And then" if any of those are clear" all of those ad#acent s !ares are cleared" etc$ 0tep 3 is rec!rsive" since yo! apply the same set of steps to clear each ad#acent s !are to a s !are with a 9:9 in it$ I am going to simplify the code for this a bit so that we can foc!s on the rec!rsive part of it$ (I will replace some code with comments that simply signify what sho!ld be done in that portion of code$) 7he f!ll e%ample is posted online !nder the 0ample ;rograms$ 5omments have been removed so the code ta&es !p less space$ 7he &ey here is .(/< if we clear a s !are and find : bombs ad#acent to it do we ma&e a rec!rsive call$ F!rthermore" we ma&e 0=>=4A/ rec!rsive calls" potentially !p to 1 of them$

int domove(char board?@?0ID=@" char realboard?@?0ID=@" int listbombs?@?2@" int row" int col!mn" int 'totalmoves) A int i" #" n!mB if (realboard?row@?col!mn@CC8'8) A DD Eit a bomb" losing moveF G else if (board?row@?col!mn@HC8I8) A DD 7his s !are was previo!sly clearedF G else A DD 7his calc!lates the J of ad#acent bombs$ n!m C n!mberbombs(row" col!mn" listbombs)B ('totalmoves)--B board?row@?col!mn@C(char)(n!mK8:8)B DD If there are no ad#acent bombs" we can rec!rsively clear$ if (n!m CC :) A DD 7races thro!gh all L s !ares in the bo% aro!nd row"col$ for (iC-6BiM2BiKK) A for (#C-6B#M2B#KK) A if (valid(rowKi"col!mnK#) NN (board?rowKi@?col!mnK#@CC8I8)) domove(board" realboard" listbombs" rowKi" col!mnK#" totalmoves)B G G G DD end-if n!mCC: ret!rn :B G DD end else G

In this code" a do!ble for loop str!ct!re helps !s iterate thro!gh all the ad#acent s !ares:
for (iC-6BiM2BiKK) A for (#C-6B#M2B#KK) A

Oasically" i and # represent the offsets for row and col!mn" respectively" for all possible ad#acent s !ares$ D!e to o!r if statement that chec&s for validity" there is no problem in accidentally calling o!r f!nction again with the e%act same row and col!mn val!e$ 7his call does nothing beca!se the if statement screens it o!t$ 7h!s" the following if statement is critical:
if (valid(rowKi"col!mnK#) NN (board?rowKi@?col!mnK#@CC8I8))

7he first cla!se in the if statement prevents array o!t of bo!nds errors$ 7he second cla!se in the if statement prevents from clearing a s !are that was previo!sly cleared$ .nly if these two tests are passed do we rec!rsively clear the s !are with the location rowKi" col!mnK# In essence" we are performing a floodfill of all ad#acent s !ares with no ad#acent bombs" starting from the initial chosen location by the !ser$

;rogramming 5ontest =%ample: Polf Fine


7he following !estion is ta&en from a high school comp!ter programming contest held at Qniversity of 5entral Florida on Ran!ary 21" 2:6:$ Its sol!tion involves a floodfill$ 7he !estion is incl!ded on the following two pages$ 7hat is followed by a disc!ssion of how to solve the problem !tiliSing the floodfill idea" followed by the code that solves the problem$ (ote: 7he inp!t for the problem (for this contest) was s!pposed to come from the &eyboard$ I have written my sol!tion so that the inp!t is read in from a file called" )golf$t%t*$ 7o f!lly test this program" one wo!ld have to test it many times with different inp!t files" since the format in which the !estion is posed only tests one case at a time$

Polf Fine
Land development company Developers-R-Us has been in constant battle with environmentalists for decades. In recent years, the company has been responsible for destroying the habitat of the Michigan monkey flower, and has faced large fines as a conse !ence. "he lawyers for this land development company have tho!ght !p a new idea - a sort of loophole in the system. "he company has p!rchased a large plot of land, b!t will not develop all of it, th!s inc!rring fines only for those areas containing monkey flowers that are ad#acent $hori%ontally, vertically, or diagonally& to developed land. "he environmental engineers of Developers-R-Us have provided yo!, the software engineer, with a series of grid maps representing the area where a new golf co!rse will be b!ilt. "hey wo!ld like to determine the area which will be covered by the proposed golf co!rse, as well as the fines the company will have to pay for b!ilding it. 'o! will be provided with a () * () grid, representing the ()) s !are acres being !sed to b!ild the golf co!rse. +ach acre of monkey flowers along the path costs ,-) ))).

Inp!t
Inp!t will consist of ten lines, each containing ten characters, where. / . - represents land not being developed / s - represents the start of the golf co!rse0 there will be e*actly one s!ch acre in the whole gridmap / d - represents an acre of developed land0 note that there may be developed land which is not connected $hori%ontally, vertically, or diagonally& to the golf co!rse, b!t this is not yo!r problem / m - represents an acre of land containing Michigan monkey flowers

.!tp!t
1rovide, on two separate lines, the n!mber of acres being developed for the golf co!rse, and the fine for b!ilding the co!rse ne*t to areas containing Michigan monkey flowers. 1ay close attention to the o!tp!t format for the fine. there m!st be a dollar sign at the beginning of the line, and a space sho!ld be !sed as tho!sands separator.

=%ample
Inp!t .......... .sd....... ..d....... ..dm...... ..d....... ..d...m... ..ddddm... .......... ...ddd.... ...mmm.... .!tp!t 10 $150 000

.!r goal is to identify how many ad#acent s !ares (directly or indirectly) to Ts- are part of the golf co!rse$ 7his indicates that we o!ght to do a floodfill starting at character Ts-$ F!rthermore" we can ass!me that o!r floodfill sho!ld go in all eight directions$ (7ho!gh this isn-t directly stated" it-s probably the best ass!mption to ma&e" since this is how we are to tell whether or not the flowers are ad#acent to the co!rse$) 7here is one more complicating factor for this problem after we do o!r floodfill: 5o!nting the ad#acent s !ares that have mon&ey flowers in them First" let-s concentrate on the floodfill: 7his will be very" very similar to 3inesweeper" e%cept that we sho!ld fill o!r s !ares with Ts- and Td- with different characters to mar& the golf co!rse$ In the following implementation" the character TU- is chosen$ 7his is an arbitrary choice$ Any choice of character that isn-t already in the grid wo!ld be fine$ Oasically" we will change the grid at the location to be filled to the character TU-$ 7hen" for each ad#acent location" we-ll see if it-s part of the co!rse (with a Td-)$ If so" we-ll contin!e the floodfill at that location$

5ode for Polf Fine Floodfill void floodfill(char grid?@?0IV=@" int %" int y) A int i"#B DD 3ar& this spot grid?%@?y@ C 8U8B DD Po thro!gh all valid ad#acent s !ares with a 8d8$ for (iC-6B iM2B iKK) for (#C-6B #M2B #KK) if (inbo!nds(%Ki"yK#) NN grid?%Ki@?yK#@CC8d8) floodfill(grid"%Ki"yK#)B G 7his sho!ld loo& very" very similar to the 3inesweeper code$ 7he only reason it-s m!ch shorter is the action we need to ta&e to clear a s !are is very simple (#!st p!tting an TU- in that slot) and there are fewer contingencies for other sit!ations$ Also" note that the initial call to this f!nction has the %-y coordinates of the spot of the Ts-" so that is why the floodfill doesn-t loo& for the character Ts- at all$ 7he rest of the code is incl!ded in the 0ample ;rograms (!nder rec!rsion) in the file golf$c$ .ne sample inp!t file is incl!ded also" called" golf$t%t$

Vous aimerez peut-être aussi