# Include <cstdio> # include <cstring> # define N 200 # define M 200int map [N] [M] = {0}; void DFS (int I, int j) {if (map [I] [j-1]) {map [I] [j-1] = 0; DFS (I, j-1 );} if (map [I] [j + 1]) {map [I] [j + 1] = 0; DFS (I, j + 1 );} if (map [i-1] [j]) {map [i-1] [j] = 0; DFS (i-1, j );} if (map [I + 1] [j]) {map [I + 1] [j] = 0; DFS (I + 1, j) ;}} int main () {int t, n, m; int I, j, count; scanf ("% d", & t); while (t --) {scanf ("% d", & n, & m); count = 0; for (I = 1; I <= n; I ++) for (j = 1; j <= m; j ++) scanf ("% d", & map [I] [j]); for (I = 1; I <= n; I ++) for (j = 1; j <= m; j ++) if (map [I] [j]) {count ++; map [I] [j] = 0; DFS (I, j);} printf ("% d \ n", count);} return 0 ;}
Let's look at this again:
# Include <cstdio> # include <cstring> # define N 200 # define M 200int map [N] [M] = {0 }; int f [4] [2] = {-}, {0,-1}; void DFS (int I, int j) {int k; map [I] [j] = 0; for (k = 0; k <4; k ++) {if (map [I + f [k] [0] [j + f [k] [1] = 1) DFS (I + f [k] [0], j + f [k] [1]) ;}} int main () {int t, n, m; int I, j, count; scanf ("% d", & t); while (t --) {scanf ("% d", & n, & m ); count = 0; for (I = 1; I <= n; I ++) for (j = 1; j <= m; j ++) scanf ("% d", & map [I] [j]); for (I = 1; I <= n; I ++) for (j = 1; j <= m; j ++) if (map [I] [j]) {count ++; map [I] [j] = 0; DFS (I, j);} printf ("% d \ n", count);} return 0 ;}
BFS:
# Include <cstdio> # include <cstring> # include <algorithm> # include <queue> # define N 200 # define M 200 using namespace std; int map [N] [M] = {0}; int f [4] [2] = {-}, {0, -1 }}; struct pool {int a, B ;}; queue <pool> v; void BFS (int I, int j) {int k; pool p, x, y; p. a = I; p. B = j; v. push (p); map [I] [j] = 0; while (! V. empty () {x = v. front (); for (k = 0; k <4; k ++) {if (map [x. a + f [k] [0] [x. B + f [k] [1]) {map [x. a + f [k] [0] [x. B + f [k] [1] = 0; y. a = x. a + f [k] [0]; y. B = x. B + f [k] [1]; v. push (y) ;}} v. pop () ;}} int main () {int t, n, m; int I, j, count; scanf ("% d", & t ); while (t --) {scanf ("% d", & n, & m); count = 0; for (I = 1; I <= n; I ++) for (j = 1; j <= m; j ++) scanf ("% d", & map [I] [j]); for (I = 1; I <= n; I ++) for (j = 1; j <= m; j ++) if (map [I] [j]) {count ++; map [I] [j] = 0; BFS (I, j);} printf ("% d \ n", count) ;}return 0 ;}