ACM PKU 1111 Image Perimeters http://acm.pku.edu.cn/JudgeOnline/problem?id=1111
广搜永远记住,下标不要错,COPY时一定要记得改下标:
#include <iostream> #include <queue> using namespace std; char rec[21][21]; bool flag[21][21]; int h[8] = {1,1,1,0,0,-1,-1,-1}; int s[8] = {1,-1,0,-1,1,0,-1,1}; int row,column,st0,st1; int sum = 0; struct node { int r; int c; node(){}; node(int x , int y) { r = x ; c = y; }; }; queue<node>myqueue; int temp(int x,int y) { int num = 0; if (x == 0 ||rec[x-1][y]== '.') num++; if (x == row-1 ||rec[x+1][y]== '.') num++; if (y == 0 ||rec[x][y-1]=='.') num++; if (y == column-1 ||rec[x][y+1]=='.') num++; return num; } bool charge (int H,int L) { if( (H >=0) && (H < row) && (L >= 0) && (L < column)) if ((rec[H][L]=='X') && (flag[H][L] == 0) ) return true; return false; } void solve(int H, int L) { if (charge(H,L)) { flag[H][L] = 1; sum += temp(H,L); myqueue.push(node(H , L)); rec[H][L] = '1'; } while (!myqueue.empty()) { int i ; for(i = 0 ;i < 8 ; i++) { int a = myqueue.front().r; int b = myqueue.front().c; if(charge(myqueue.front().r + h[i] ,myqueue.front().c + s[i])) { myqueue.push(node(myqueue.front().r + h[i] , myqueue.front().c + s[i])); rec[myqueue.front().r + h[i]][myqueue.front().c + s[i]] = '1'; sum += temp(myqueue.front().r + h[i],myqueue.front().c + s[i]); } } myqueue.pop(); } } int main () { while (cin>>row>>column>>st0>>st1) { int i, j; memset(flag,0,sizeof (flag)); sum = 0; if (row==0 && column==0 && st0==0 && st1==0 ) break; for (i=0; i<row; i++) for (j=0; j<column;j++) cin >> rec[i][j]; solve(st0-1,st1-1) ; cout<< sum << endl; } return 0; }