One of the Dfs getting Started

Source: Internet
Author: User

The implementation of depth-first search is simple, and two factors need to be controlled:

1. Elements that have already been accessed are no longer accessible, and the elements that are inaccessible are added to the actual topic (barriers)

2. Cross-border This situation is not allowed

Take the 1312 Red and Black as an example, this is a typical DFS topic

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

The main idea: ' @ ' stands for the starting position, '. ' Represents the black point (which can be traversed), ' # ' represents the red dot (barrier) requires statistics to cover up to how many black dots

Topic Analysis: Determine starting position, start DFS, if not illegal location, count once, recursive search four directions (up, down, left, right)-end

Attach My code (for reference only):

#include <cstdio>#include<cstring>Const intMAXN = -+Ten;CharA[MAXN][MAXN];intW, H, IDX[MAXN][MAXN], CNT;intDfsintRintCintID) {    if(R <0|| R >= H | | C <0|| C >= W)return 0; if(Idx[r][c] >0|| A[R][C] = ='#')return 0; IDX[R][C]=ID; CNT++;  for(inti =-1; I <=1; i++)         for(intj =-1; J <=1; J + +)            if((i = =0&& J! =0)|| (I! =0&& J = =0)) Dfs (R+i, c+j, id);}intMain () {intR, C;  while(~SCANF ("%d%d", &w, &h)) {CNT=0; if(W = =0&& h = =0) Break;  for(inti =0; I < H; i++) scanf ("%s", A[i]); memset (IDX,0,sizeof(IDX));  for(inti =0; I < H; i++)             for(intj =0; J < W; J + +)                if(A[i][j] = ='@') {R=i; C=J; } DFS (R, C,1); printf ("%d\n", CNT); }    return 0;}
please refer to it.

One of the Dfs getting Started

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.