/*572-oil Deposits---dfs to find the number of blocks: from each @ to traverse the @ around it. Each time you visit a grid to give it a unicom number, before the visit, first check whether he---already numbered, thus avoiding a lattice repeated access multiple--*/#define _crt_secure_no_deprecate#include<iostream > #include <string.h> #include <algorithm>using namespace Std;const int maxn = + + 5;char M[MAXN][MAXN]; int idx[maxn][maxn];int m, n;void dfs (int r, int c, int id) {if (R < 0 | | C < 0 | | r >= N | | c >= m) return; Out of Bounds if (idx[r][c]>0| | m[r][c]!= ' @ ') return; have been visited, or not @idx[r][c] = ID; The Unicom component number for (int dr =-1; Dr <= 1; dr++) {//scan 8 directions around it for (int dc =-1; DC <= 1; dc++) if (dr | | dc) DFS (Dr + R, DC + c, id);}} int main () {while (scanf ("%d%d", &n, &m) && m&&n) {for (int i = 0; i < n; i++) scanf ("%s", M[i]); int cnt = 0;memset (idx, 0, sizeof (IDX)); No access for (int i = 0; i < n;i++) for (int j = 0; J < m; J + +) {//If not currently visited, and the current position character is @if (idx[i][j] = 0 && m[i ][J] = = ' @ ') Dfs (i, J, ++cnt);} printf ("%d\n", CNT);} return 0;}
Using DFS to find the number of Unicom blocks