DFS Getting started two---DFS seeking connectivity blocks

Source: Internet
Author: User
Tags add numbers

It is also a typical problem to find the connected block with DFS, and the process of multi-dimensional array connecting block is also called "seed filling".

We add numbers to the connected blocks that are traversed each time, so that you can avoid a lattice access multiple times. The typical problem is the "eight-block problem". That is, any two squares are located adjacent to each other (up and down diagonally a total of eight positions), then in a connected block. Typical example: HDU 1241 oil deposits

Portal: http://acm.hdu.edu.cn/showproblem.php?pid=1241

Title Description: input m row n column character matrix, statistical character "@" to form the number of eight connected blocks.

Test Instructions Analysis: Read data, through a double loop traversal of the graph, encountered ' @ ' and has not been accessed->dfs its connected block and labeled--output

Code (for reference only):

#include <cstdio>#include<cstring>Const intMAXN = -+Ten;CharA[MAXN][MAXN];intN, M, IDX[MAXN][MAXN];voidDfsintRintCintID) {    if(R <0|| R >= m | | C <0|| C >= N)return ; if(Idx[r][c] >0|| A[R][C]! ='@')return ; IDX[R][C]=ID;  for(inti =-1; I <=1; i++)         for(intj =-1; J <=1; J + +)            if(I! =0|| J! =0) Dfs (R+i, c+j, id);}intMain () { while(~SCANF ("%d%d", &m, &N)) {        if(n = =0&& m = =0) Break;  for(inti =0; I < m; i++) scanf ("%s", A[i]); memset (IDX,0,sizeof(IDX)); intCNT =0;  for(inti =0; I < m; i++)             for(intj =0; J < N; J + +)                if(Idx[i][j] = =0&& A[i][j] = ='@') Dfs (I, J, + +)CNT); printf ("%d\n", CNT); }    return 0;}
View Code

DFS Getting started two---DFS seeking connectivity blocks

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.