Challenge Program 2.1.4 Exhaustion Search >> Depth First search

Source: Internet
Author: User

{' W ', '. ', '. ', ' w ', '. '},{' W ', '. ', '. ', '. ', '. ', '. ', '. ', '. ', '},{', '. ', '},{', '. ', '. ', '. ', '. ', '. ', '. ', '. ', '. ', '. ', ' W ' example, where there are 5 of stagnant water

title: garden with N*m lattice, w indicates stagnant water, '. ' Said dry ground, the water near the 8 areas as long as there is water, then these two connections, and counted as the same water, asked a total number of water?

idea: exhaustion Search, O (n*m), search for stagnant water becomes '. ', and search for connected water to turn it into '. ' Until this water search is over, and a+=1, where the water is all changed to '. '

1#include <stdio.h>2 voidDfsintXinty);3 voidsolve ();4     intn=5, m=5;5         Charch[5][5]={6{'W','.','.','W','.'},7{'W','.','.','.','.'},8{'.','.','.','W','.'},9{'W','.','.','.','.'},Ten{'W','.','W','W','W'} One                       }; A intMain () - { -  the solve (); -     return 0; - } -  + voidDfsintXinty) - { +ch[x][y]='.'; A      for(intx1=-1; x1<=1; x1++) at          for(inty1=-1; y1<=1; y1++) -     { -         intnx=x+x1,ny=y+Y1; -         if(nx>=0&&nx<n&&ny>=0&&ny<m&&ch[nx][ny]=='W')//nx,ny cannot go beyond the garden - DFS (nx,ny); -     } in     return ; - } to  + voidSolve () - { the     intA=0; *      for(intI=0; i<n;i++) $          for(intk=0; k<m;k++)Panax Notoginseng         if(ch[i][k]=='W') -         { the DFS (i,k); +a++; A         } theprintf"%d\n", a); +}

The code for 5*5,5 blocks of stagnant water is shown here.

Tips: Depth-First search for DFS, starting at the very beginning, traversing all possibilities, manipulating or enumerating them.

Challenge Program 2.1.4 Exhaustion Search >> Depth First search

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.