• 独立岛问题的BFS,DFS求解


    #include #include using namespace std; #define _CRT_SECURE_NO_WARNINGS #define MAX 20 #define queue_init (head=tail=0) #define queue_is_empty (head==tail) #define en_queue(x) (queue[tail++]=x) #define de_queue (queue[head++]) struct point{ int x; int y; }; struct point queue[MAX*MAX]; int head, tail; int a[] = { 1, -1, 0, 0 }; int b[] = { 0, 0, 1, -1 }; int N, M; int map[MAX][MAX], vis[MAX][MAX]; int Ans; int color; int sum; int maxmin; void bfs(int flag,int i, int j){ queue_init; point start; start.x = i; start.y = j; en_queue(start); map[start.x][start.y] = flag; vis[start.x][start.y] = 1; sum=1; while (!queue_is_empty){ point p = de_queue; for (int k = 0; k < 4; k++){ point next; next.x = p.x + a[k]; next.y = p.y + b[k]; if (next.x<1 || next.x>N || next.y<1 || next.y>M) continue; if (vis[next.x][next.y] == 1) continue; if (map[next.x][next.y]>0){ map[next.x][next.y] = flag; sum++; vis[next.x][next.y] == 1; en_queue(next); } } } maxmin = sum > maxmin ? sum : maxmin; } int main(){ freopen("input.txt","r",stdin); int T; cin >> T; for (int t = 1; t <= T; t++){ color = 0; cin >> N >> M; for (int i = 1; i <= N; i++){ for (int j = 1; j <= M; j++){ cin >> map[i][j]; } } for (int i = 1; i <= N; i++){ for (int j = 1; j <= M; j++){ if (map[i][j] > 0){ bfs(--color,i,j); } } } cout << "#" << t << " " << -color <<" "<< maxmin< using namespace std; #define _CRT_SECURE_NO_WARNINGS int T, N, M, sum,max,a[20][20], book[20][20]; int Next[4][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; void dfs(int x, int y, int color){ int tx, ty, k; //染色当前坐标 a[x][y] = color; //循环 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 (a[tx][ty] >= 1 && book[tx][ty] == 0){ sum++; //标记走过 book[tx][ty] = 1; //开始尝试下一个点 dfs(tx,ty,color); if (sum > max) max = sum; } } return; } int main(){ int i, j, t, num = 0; freopen("input.txt","r",stdin); setbuf(stdout, NULL); //输入数据 cin >> T; for (t = 1; t <= T; t++){ cin >> N >> M; for (i = 1; i <= N; i++) for (j = 1; j <= M; j++) cin >> a[i][j]; //判断传入dfs函数的参数,调用dfs() for (i = 1; i <= N; i++){ for (j = 1; j <= M; j++){ if (a[i][j] >= 1){ num--; book[i][j] = 1; dfs(i, j, num); } } } //输出 cout << -num << " " << max << endl; for (i = 1; i <= N; i++){ for (j = 1; j <= M; j++) printf("%3d", a[i][j]); cout << endl; } } while (1); return 0; }
  • 相关阅读:
    32位与64位操作系统到底有什么区别呢?
    chr()、unichr()和ord()
    Python map filter reduce
    as3.0横向渐变发光字
    Python time format
    Python 使用sys重定向
    as3.0给文字加纹理效果
    my first python
    字符编码(转)
    SWFTOOLS学习笔记一(转)
  • 原文地址:https://www.cnblogs.com/wujixing/p/6293635.html
Copyright © 2020-2023  润新知