北大 ACM 1111题

北大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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值