分治递归——Red and Black

tech2022-07-14  152

原题链接:POJ—1979 题目大意:题目意思很简单,给出起始点"@",可以走的点为".",不可以走的点为"#",问所有能走的点有多少个。 题目解法:水题,DFS递归解决就好了,注意递归条件的判断,以及比较坑的点就是输出的时候,看好什么时候用getchar(),来消enter。 题目代码:

#include<stdio.h> #include<string.h> int flag[25][25]; char maps[25][25]; int w,h; void DFS(int x,int y) { flag[x][y]=1; if(x+1<w&&maps[x+1][y]=='.'&&flag[x+1][y]==0) DFS(x+1,y); if(x-1>=0&&maps[x-1][y]=='.'&&flag[x-1][y]==0) DFS(x-1,y); if(y+1<h&&maps[x][y+1]=='.'&&flag[x][y+1]==0) DFS(x,y+1); if(y-1>=0&&maps[x][y-1]=='.'&&flag[x][y-1]==0) DFS(x,y-1); } int main() { while(scanf("%d%d",&h,&w)!=EOF) { getchar(); int x,y,num=0; if(h==0&&w==0) break; memset(flag,0,sizeof(flag)); for(int i=0;i<w;i++) { for(int j=0;j<h;j++) { scanf("%c",&maps[i][j]); if(maps[i][j]=='@') { x=i; y=j; } } getchar(); } DFS(x,y); for(int i=0;i<w;i++) { for(int j=0;j<h;j++) { if(flag[i][j]==1) num++; } } printf("%d\n",num); } return 0; }

欢迎留言哦!

最新回复(0)