1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include <stdio.h> int book[51][51]; int a[51][51]; int n, m, sum = 1 , num; void dfs(int x, int y,int num) { int next[4][2] = { {1,0},{0,-1},{-1,0},{0,1} }; int tx, k, ty; for (k = 0; k <= 3; k++) { tx = x + next[k][0]; ty = y + next[k][1]; if (tx<1 || tx>n || ty<1 || ty>m) continue; if (book[tx][ty] == 0 && a[tx][ty] >= 1) { book[tx][ty] = 1; a[tx][ty] = num; dfs(tx, ty,num);
} } return; } int main() { int i, j, startx, starty; printf("请输入你要输入几行几列的地图:"); scanf_s("%d %d", &n, &m); printf("请输入地图:\n"); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) scanf_s("%d", &a[i][j]); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { if (a[i][j] > 0) { num--; a[i][j] = num; dfs(i, j, num); } } printf("染色后的小岛地图是:\n"); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { printf("%3d", a[i][j]); } printf("\n"); } printf("小岛的个数是:%d", -num); getchar(); getchar(); return 0;
}
|