求图像周长问题



#include<iostream>
#include<queue>

using namespace std;

queue<int>q;

int m,n,x,y;
int z;
int answer[100],cnt=0;//存放答案
int used[1000]={0};//看该小方格是否判断过,1为判断过,0为未判断
int length;//存放周长
char a[100][100];

void bfs();
void init();
int canmoveto(int,int);
int moveto(int,int);
void len(int);
void output();
void reused();

int main()
{
 int i,j;
 
 while(1)
 {
  cin>>m>>n>>x>>y;
  if(m==0&n==0&&x==0&y==0)
  {
   break;
  }
  
  else
  {
   z=(x-1)*n+y-1;//注意题中是从一行一列开始的,先把它弄成零行零列开始的
   for(i=0;i<m;i++)
   {
    for(j=0;j<n;j++)
    {
     cin>>a[i][j];
    }
   }
   init();
   
   bfs();
   
   reused();
  }
 }
 output();
 return(0);
}

void bfs()
{
 int u,v;
 int k=0;
 
 while(!q.empty())
 {
  u=q.front();
  q.pop();
  len(u);
  for(k=0;k<8;k++)//k为0,1,2,3,4,5,6,7:分别表示向i所表示方向移动一格进行判断。 (顺时针来从0开始)
  {
   if(canmoveto(u,k))//判断是否有必要判断下一步(是否合法)
   {
    v=moveto(u,k);
    
    if(used[v]!=1&&a[v/n][v%n]=='X')//如果没有用过,那么让v进入数列
    {
     q.push(v);
     used[v]=1;        
    }
   }
  }
 }
 answer[cnt]=length;
 cnt++;
 length=0;
}

void init()
{
 q.push(z);
 used[z]=1;
}

int canmoveto(int u,int k)
{
 int row,col;
 row=u/n;
 col=u%n;
 if(k==0&&row-1>=0)
 {
  return(1);
 }
 else if(k==1&&row-1>=0&&col+1<=n-1)
 {
  return(1);
 }
 else if(k==2&&col+1<=n-1)
 {
  return(1); 
 }
 else if(k==3&&row+1<=m-1&&col+1<=n-1)
 {
 
  return(1);
 } 
 else if(k==4&&row+1<=m-1)
 {
  return(1);
 } 
 else if(k==5&&row+1<=m-1&&col-1>=0)
 {
  return(1);
 } 
 else if(k==6&&col-1>=0)
 {
  return(1);
 } 
 else if(k==7&&col-1>=0&&row-1>=0)
 {
  return(1);
 }
 else
 {
  return(0);
 }
}

int moveto(int u,int k)
{
 int row1,col1;
 row1=u/n;
 col1=u%n;
 if(k==0)
 {
  row1=row1-1;
 }
 else if(k==1)
 {
  row1=row1-1;
  col1=col1+1;
 }
 else if(k==2)
 {
  col1=col1+1;
 }
 else if(k==3)
 {
  row1=row1+1;
  col1=col1+1;
 } 
 else if(k==4)
 {
  row1=row1+1;
 } 
 else if(k==5)
 {
  row1=row1+1;
  col1=col1-1;
 } 
 else if(k==6)
 {
  col1=col1-1;
 } 
 else if(k==7)
 {
  col1=col1-1;
  row1=row1-1;
 } 
 
 return(row1*n+col1);
}

void len(int u)
{
 int row,col;
 row=u/n;
 col=u%n;
 
 if(row-1<0||a[row-1][col]=='.')//上下左右来判断,加周长 (若为空或‘.’那么周长加一)
 {
  length++; 
 }
 if(row+1>m-1||a[row+1][col]=='.')
 {
  length++;
 }
 if(col-1<0||a[row][col-1]=='.')
 {
  length++;
 }
 if(col+1>n-1||a[row][col+1]=='.')
 {
  length++;
 }
}

void output()
{
 int i;
 for(i=0;i<cnt;i++)
 {
  cout<<answer[i]<<endl;
 }
}

void reused()
{
 int i;
 for(i=0;i<=m*n-1;i++)
 {
  used[i]=0;
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值