《算法竞赛入门经典2ndEdition 》习题3-6 纵横字谜的答案(Crossword Answers, Uva232)

这个还好,一次AC,昨天晚上编了一小会,今天早上早起稍微调试了下,把样例数据弄对之后submit就一次AC了,现在刚刚有时间发上来,下面看代码吧。

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int maxn = 10;
char s[maxn + 10][maxn + 10];
int num[maxn + 10][maxn + 10];
int cnt;

bool check(int x, int y)//check if it is eligible
{
  if(num[x][y] == -1) return false;
  if(x == 0 || y == 0) 
  {
    num[x][y] = ++cnt;
    return true;
  }
  if(num[x-1][y] == -1 || num[x][y-1] == -1) 
  {
    num[x][y] = ++cnt;
    return true;
  } 
}
bool across(int x, int y)
{
  if(y == 0) 
    if(num[x][y] > 0)
      return true;
    else return false;
  else 
    if(num[x][y] > 0 && num[x][y-1] == -1) 
      return true;
    else return false;
}
bool down(int x, int y)
{
  if(x == 0) 
    if(num[x][y] > 0)
      return true;
    else return false;
  else 
    if(num[x][y] > 0 && num[x-1][y] == -1) 
      return true;
    else return false;
}

int main()
{     
  freopen("New Text Document.txt","r",stdin);
  freopen("Output.txt","w",stdout);
  int r, c, p = 0;
  while(scanf("%d%d", &r, &c) && r && c)
  {
    if(p) printf("\n");
    printf("puzzle #%d:\n", ++p);
    cnt = 0;
    memset(s, 0, sizeof(s));
    memset(num, 0, sizeof(num));
    getchar();
    for(int i = 0; i < r; i++)
    {
      for(int j = 0; j < c; j++)
      {
        scanf("%c", &s[i][j]);
        if(s[i][j] == '*') num[i][j] = -1;
      }
      char ch = getchar();
    }
    //for(int i = 0; i < r; i++)
//    {
//      for(int j = 0; j < c; j++)
//      {
//        printf("%c", s[i][j]);
//        
//      }
//      cout<<endl;
//    }

    for(int i = 0; i < r; i++)
      for(int j = 0; j < c; j++)
        check(i,j);

    //for(int i = 0; i < r; i++)
//    {
//      for(int j = 0; j < c; j++)
//      {
//        printf("%d", num[i][j]);
//        
//      }
//      cout<<endl;
//    }

    printf("Across\n");
    for(int i = 0; i < r; i++)
      for(int j = 0; j < c; j++)
        if(across(i,j))//start of across
        { 
          printf("%3d.", num[i][j]);
          while(j < c && s[i][j] != '*')
            printf("%c",s[i][j++]);
          printf("\n");
        }
    printf("Down\n");
    for(int i = 0; i < r; i++)
      for(int j = 0; j < c; j++)
        if(down(i,j))//start of down
        { 
          printf("%3d.", num[i][j]);
          int p = i;
          while(p < r && s[p][j] != '*')
            printf("%c",s[p++][j]);
          printf("\n");
        }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值