Question: There is a lattice matrix with m rows and n columns. Each lattice is either @ or *, the two grids are connected. if and only when the two grids are @, and one grid is adjacent to the other, horizontal, vertical, or diagonal, that is, one grid is within the eight grids around the other. Finally, calculate the number of connected blocks.
Train of Thought: Just like the example in the book, it's just a 01, A * @. Just change it a bit. That is, recursive depth-first traversal through DFS (x, y.
Code:
#include<stdio.h>#include<string.h>#define MAX 110void dfs(int x,int y);char mat[MAX][MAX];int vis[MAX][MAX];int m,n;int main(){ while(scanf("%d%d",&m,&n)==2 && m) { memset(mat,'*',sizeof(mat)); memset(vis,0,sizeof(vis)); char s[MAX]; for(int i=0;i<m;++i) { scanf("%s",s); for(int j=0;j<n;++j) mat[i+1][j+1]=s[j]; } int cnt=0; for(int i=1;i<=m;++i) for(int j=1;j<=n;++j) if(mat[i][j]=='@' && !vis[i][j]) { dfs(i,j); cnt++; } printf("%d\n",cnt); } return 0;}void dfs(int x,int y){ if(mat[x][y]=='*' || vis[x][y]) return ; vis[x][y]=1; dfs(x-1,y-1); dfs(x-1,y); dfs(x-1,y+1); dfs(x,y-1); dfs(x,y+1); dfs(x+1,y-1); dfs(x+1,y); dfs(x+1,y+1); }
Ultraviolet A 572 Oilfield