DFS 模板
程序员文章站
2022-07-10 09:18:56
...
#include<cstdio> #include<cstring> #define MAXN 1000 int map[MAXN][MAXN]; bool visit[MAXN][MAXN]; int n,m; int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; void DFS(int x, int y) { printf("(%d,%d)",x,y); visit[x][y] = true; int xx,yy; for(int i=0;i<4;i++) { xx = x+dir[i][0]; yy = y+dir[i][1]; if(xx<0||yy<0||x>m||y>n) continue; if(map[xx][yy]&& !visit[xx][yy]) { DFS(xx,yy); } } } int main() { memset(map,0,sizeof(map)); memset(visit,false,sizeof(visit)); printf("Enter the width and height of map\n"); scanf("%d %d",&m,&n); printf("How many points are in the map"); int num; scanf("%d",&num); printf("Then, Enter every point(x,y) in the console\n"); while(num--) { int x,y; scanf("%d %d",&x,&y); map[x][y] = 1; } for(int i=0;i<m;i++) for(int j=0;j<n;j++) if(map[i][j] && !visit[i][j]) DFS(i,j); return 0; } /*测试数据 0 0 0 2 1 1 1 2 1 3 2 0 2 1 3 1 3 2 */