Programming Algorithm-Shuidao quantity code (c)

Source: Internet
Author: User
Shuidao's quantity code (c)


Address: http://blog.csdn.net/caroline_wendy


Question: There is a garden of N * m in size, and water accumulates after the rain. The water in the eight connections is considered to be connected together. How many sinks are there in the garden.


UseDeep Priority Search (DFS)FromEight directionsSearch until it is foundAll connected Stagnant Water. AgainSpecify the next wa,Until there are no sinksUntil.

Then allTimes of deep Priority SearchThat is, the number of sinks.Time complexity O (8 * m * n) = O (M * n).


Code:

 

/* * main.cpp * *  Created on: 2014.7.12 *      Author: spike */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>class Program {static const int MAX_N=20, MAX_M=20;int N = 10, M = 12;char field[MAX_N][MAX_M+1] = {"W........WW.",".WWW.....WWW","....WW...WW.",".........WW.",".........W..","..W......W..",".W.W.....WW.","W.W.W.....W.",".W.W......W.","..W.......W."};void dfs(int x, int y) {field[x][y] = ‘.‘;for (int dx = -1; dx <= 1; dx++) {for (int dy = -1; dy <= 1; dy++) {int nx = x+dx, ny = y+dy;if (0<=dx&&nx<N&&0<=ny&&ny<=M&&field[nx][ny]==‘W‘) dfs(nx, ny);}}return;}public:void solve() {int res=0;for (int i=0; i<N; i++) {for (int j=0; j<M; j++) {if (field[i][j] == ‘W‘) {dfs(i,j);res++;}}}printf("result = %d\n", res);}};int main(void){Program P;P.solve();    return 0;}


Output:

result = 3










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.