北大 ACM 1111题

来源:互联网 发布:法线贴图制作软件 编辑:程序博客网 时间:2024/05/16 04:54

北大ACM 网站题 1111,

http://poj.org/problem?id=1111

题目:

求图像的周长。

 

利用广度优先解决的代码:

#include <stdio.h>
#include <stack>
using namespace std;
char Picture[20][20];
int perimeter=0;
int MaxRow,MaxCol;
stack<int> OpenStack;
void readData(int row , int col)
{
 int i,j;
 fflush(stdin);
 for(i=0; i<row ;i++)
 {
  for(j=0 ; j<col ;j++)
    Picture[i][j]=getchar();
  fflush(stdin);
 }
}

void place(int x ,int y)
{
 Picture[x][y]='A';
}

int isBound(int x,int y)
{
 if(x==-1 || x==MaxRow || y==-1 || y==MaxCol )
  return 1;
 else if(Picture[x][y]=='.')
  return 1;
 return 0;
}

int canPlace(int x ,int y)
{
 if(x>=0 && x<MaxRow && y>=0 && y<MaxCol)
  if(Picture[x][y]=='X')
   return 1;
 return 0;
}

void search(int row , int col)
{
 int tempRow,tempCol,tempInt;
 int i,j;
 place(row,col);
 OpenStack.push(row*MaxCol +col);
 while(!OpenStack.empty())
 {
  tempInt =OpenStack.top();
  OpenStack.pop();
  row=tempInt/MaxCol;
  col=tempInt%MaxCol;
 
  for(i=-1 ; i<=1 ;i++)
   for(j=-1 ;j<=1 ;j++)
    if(!(i==0&&j==0))
    {
     tempRow=row+i;
     tempCol=col+j;
     if((i==0 || j==0)&&isBound(tempRow,tempCol))
      perimeter++;
     else
      if(canPlace(tempRow,tempCol))
      {
       place(tempRow,tempCol);
       OpenStack.push(tempRow*MaxCol+tempCol);
      }
   
    }
 }
}

int main()
{
 int x,y;
 
 scanf("%d %d %d %d",&MaxRow,&MaxCol,&x,&y);
 readData(MaxRow,MaxCol);

 while(MaxRow!=0)
 {
  search(x-1,y-1);
  printf("%d/n",perimeter);
  perimeter=0;
  scanf("%d %d %d %d",&MaxRow,&MaxCol,&x,&y);
  readData(MaxRow,MaxCol);
 }

 return 0;
}

原创粉丝点击