Oilfield problems (L-Brute force solution, DFS)
Description
The Geosurvcomp Geologic Survey company are responsible for detecting underground oil deposits. Geosurvcomp works with one large rectangular region of land at a time, and creates a grid that divides the land into Numer OUs square plots. It then analyzes each plot separately, using a sensing equipment to determine whether or not of the plot contains oil. A plot containing oil is called a pocket. If the pockets is adjacent, then they is part of the same oil deposit. Oil deposits can is quite large and may contain numerous pockets. Your job is to determine how many different oil deposits be contained in a grid.
Input
The input contains one or more grids. Each of the grids begins with a line containing M and N, the number of rows and columns in the grid, separated by a single space. If m = 0 It signals the end of the input; Otherwise 1 <= m <= and 1 <= n <= 100. Following this is m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and are either ' * ', representing the absence of oil, or ' @ ', representing a oil PO Cket.
Output
is adjacent horizontally, vertically, or diagonally. An oil deposit won't contain more than pockets.
Sample Input
1 1*3 5*@*@***@***@*@*1 8@@****@*5 5 ****@*@@*@*@**@@@@*@@@**@0 0
Sample Output
0122
Main topic:
@ stands for oil fields, * represents no oilfields. The adjacent two @ represents an oil field, and a two-dimensional array is entered to find out how many oilfields are in this array?
Analysis:
1. This is a typical eight-queen problem that requires a traversal of the search from 8 directions
2.DFS (Depth-first search), recursive method
3. After finding a @, traverse from 8 directions and record sum++
Code:
1#include <cstdio>2#include <iostream>3 using namespacestd; 4 5 Charmap[101][101]; 6 intn,m,sum; 7 8 voidDfsintIintj)9 { Ten if(map[i][j]!='@'|| i<0|| j<0|| i>=m| | J>=n)//not an oil field or boundary . One return; A Else //Search from 8 directions - { -map[i][j]='!'; theDFS (I-1, J-1); -DFS (I-1, J); -DFS (I-1, j+1); -DFS (i,j-1); +DFS (i,j+1); -DFS (i+1, J-1); +DFS (i+1, J); ADFS (i+1, j+1); at } - } - - intMain () - { - inti,j; in while(SCANF ("%d%d", &m,&n)! =EOF) - { to if(m==0|| n==0) + Break; -sum=0; the for(i=0; i<m;i++) * for(j=0; j<n;j++) $Cin>>Map[i][j]; Panax Notoginseng for(i=0; i<m;i++) - { the for(j=0; j<n;j++) + { A if(map[i][j]=='@')//centered on map[i][j]== ' @ ' the { + DFS (I,J); -sum++; $ } $ } - } -printf"%d\n", sum); the } - Wuyi return 0; the}
View Code
This problem is obviously similar to the 8 queen question, so the solution is very simple.
POJ 1562 (L-Brute force solution, DFS)