题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1312
方法:对探寻到的点的数目累加的时候,可以选择在刚探寻到一个点时对数目加1,也可以在一个新探寻到的点开始进行新一层探寻的时候对数目加1,即前者记录有多少个点进队列,后者记录有多少出。
感想:第2次做的时候选择了第2种方法,两种方法都可以过,本代码使用第一种。
代码:
View Code
#include <iostream> #include <queue> using namespace std; int rowsCount,columsCount; bool visited[25][25]; char tiles [25][25]; int derection[4][2]; char red = '#'; char man='@'; char black ='.'; struct point { int x,y; }; bool canGo(int x,int y) { if(x<0||x>=rowsCount ||y<0||y>=columsCount) return false; if(tiles[x][y] == red) return false; return !visited[x][y]; } int search(int startX, int startY) { queue<point*> Q; point* start = (point*)malloc(sizeof(point)); start->x = startX; start->y = startY; visited[start->x][start->y] = true; Q.push(start); int result = 0; while(!Q.empty()) { point* tempP = Q.front(); Q.pop(); result++; for(int i=0;i<4;i++) { int x = derection[i][0]+tempP->x; int y = derection[i][1]+tempP->y; if(canGo(x,y)) { point* newP = (point*)malloc(sizeof(point)); newP->x = x; newP->y = y; visited[x][y] = true; Q.push(newP); } } delete[] tempP; } while(!Q.empty()) { delete [] Q.front(); Q.pop(); } return result; } void main() { derection[0][0] = 1;derection[0][1] = 0; derection[1][0] = 0;derection[1][1] = 1; derection[2][0] = -1;derection[2][1] = 0; derection[3][0] = 0;derection[3][1] = -1; int s=0,t=0; while( scanf("%d %d",&columsCount,&rowsCount) && columsCount!=0 && rowsCount!=0 ) { for(int i =0;i<rowsCount;i++) for(int j=0;j<columsCount;j++) { cin>>tiles[i][j]; visited[i][j]= false; if(tiles[i][j]==man) { s = i; t = j; tiles[i][j] = black; } } cout<<search(s,t)<<endl; } }