/******************************************************************************

                    「四角に切れ」解法プログラム

         copyright (c) 1995  by T.Mori <mori@forest.dnj.ynu.ac.jp>
	 All right reserved.

	 $Author: mori $
	 $Revision: 1.6 $
	 $Date: 1995/08/18 11:09:53 $


0.はじめに

  このプログラムは森辰則(横浜国大・電子情報工学科)が横浜国立大学電子情
  報工学特別実験のために独自に開発したものです．
  著作権は放棄しませんが，GNU GENERAL PUBLIC LICENSE を適用するものと
  し，このプログラムのいかなる部分の変更・流用も自由とします．
  バグなどがありましたら，上記アドレスまで連絡を頂ければ幸いです．

1.インストールの方法

  普通にCコンパイラでコンパイルして下さい．ただし，ANSI C 準拠のコンパ
  イラが必要です．例えば GNU CC をお持ちでしたら，次のようにします．

  gcc -O -o shikaku shikaku.c

2.使い方

  このプログラムは以下のように起動します．

  shikaku [-d] [-r] [-p] [-o 出力ファイル名] [-v] [データファイル名]

      -d                : 途中結果も表示するデバッグモード
      -r                : プログラム可読出力モード
      -p                : 問題清書モード(解を求めない)
      -o 出力ファイル名 : 出力ファイルの名前
      -v                : バージョンの表示
      ファイル名        : データファイルの名前

  データファイルの名前を省略すると，標準入力からデータファイルが読み込
  まれます．また，出力ファイルを指定しない場合は標準出力に結果が出力されます．


3.データ形式

  このプログラムのデータ形式は次のようになっています．

  <Data>            ::=  <Line>+
  <Line>            ::=  <Comment>|<Data Line>
  <Data Line>       ::=  <Mark>+ '\n'
  <Mark>            ::=  <Number Mark>|<non-Number Mark>
  <Number Mark>     ::=  <Digit>+
  <Digit>           ::=  '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
  <non-Number Mark> ::=  '.'
  <Del>             ::=  <Digit>, <non-Number Mark> 以外の文字
  <Comment>         ::=  '#' <Any Character>* '\n'

  空白文字以外にも'+''=''|' を区切り文字にしてありますので，データをき
  れいに記述することができます．また，行頭に'#'のある行はコメントになり
  ますので，任意の文字を記述できます．
  

  例えば，以下のデータは正しいデータを表します．

      例1)
        #
        # Some comments
        #
	 . (5) .  .  .  .
	 .  .  .  .  . (2)
	 .  . (3) .  . (4)
	(6) .  . (3) .  .
	(8) .  .  .  .  .
	 .  .  .  . (5) .

      例2)
      ######################################
      # ニコリ 1995年7/8月号 (Vol.55) p.22 #
      # 「四角に切れ」説明用問題           #
      ######################################
      +---+---+---+---+---+---+
      | .   5   .   .   .   . |
      +   +   +   +   +   +   +
      | .   .   .   .   .   2 |
      +   +   +   +   +   +   +
      | .   .   3   .   .   4 |
      +   +   +   +   +   +   +
      | 6   .   .   3   .   . |
      +   +   +   +   +   +   +
      | 8   .   .   .   .   . |
      +   +   +   +   +   +   +
      | .   .   .   .   5   . |
      +---+---+---+---+---+---+

******************************************************************************/
#ifndef lint
  static char shikaku_version[] = "$Header: /home/forest/mori/src/shikaku/RCS/shikaku.c,v 1.6 1995/08/18 11:09:53 mori Exp mori $";
#endif 


#include <stdio.h>
#include <malloc.h>

/* booleanの定義 */
#ifndef TRUE
#define TRUE (1)
#define FALSE (0)
#endif

/* 「タイル」(= 切り方の一つの可能性)のデータ表現 */
struct tile {
  int sx;
  int sy;
  int ex;
  int ey;
  int valid;
  struct tile *next;
};

/* 「領域」のデータ表現．複数のタイルからなる */
struct area_data {
  unsigned char sym;
  int x;
  int y;
  int extent;
  struct tile *tile;
  int fixed;
  struct area_data *next;
};

/* 解のリスト */
struct board_list {
  unsigned char **board;
  struct board_list *next;
};

/* 大域データ */
struct area_data *area_data_ptr = (struct area_data *)NULL;
struct area_data *fixed_area_data_ptr = (struct area_data *)NULL;
unsigned char **board,**old_board, **org_board, **work_board;
struct board_list *board_list;
int height=0;
int width=0;
/* 盤面内のデータ */
#define UNKNOWN	'.'
#define MULTI	'*'

/* コマンドライン引数に関連する大域変数 */
FILE *infp = stdin;		/* 入力ファイルポインタ */
FILE *outfp = stdout;		/* 出力ファイルポインタ */
int debug_mode = FALSE;		/* デバッグモードのフラグ */
int ans_mode = TRUE;		/* 求解モードのフラグ */
int prog_readable_mode = FALSE;	/* 読み込み可能モードのフラグ */
char *progname;			/* 起動時のプログラム名 */

/* プロトタイプ宣言 */
void read_data(FILE *fp);
void init_data(void);
void solve(void);
void search_answers(unsigned char **b, struct area_data *ad);
void print_board(FILE *fp, unsigned char **b);
void pretty_print_board(FILE *fp, unsigned char **b, int print_ans, int prog_readable);
void usage(void);
unsigned char get_sym(void);
struct tile *make_tiles(int x, int y, int extent);
void print_data(unsigned char **b);
void copy_board(unsigned char **dest, unsigned char **src, int copy_unknown);
void clear_multi_mark(unsigned char **b);
void set_unknown_mark(unsigned char **b);
unsigned char **alloc_board(void);
void free_board(unsigned char **b);

/* メイン */
void
main(int argc, char *argv[])
{
  int c,i;
  struct board_list *bl;
  extern char *optarg;
  extern int optind,opterr;

  progname = argv[0];

  while ((c=getopt(argc,argv,"dpro:v")) != EOF) {
    switch (c) {
    case 'd':
      debug_mode = TRUE;
      break;
    case 'p':
      ans_mode = FALSE;
      break;
    case 'r':
      prog_readable_mode = TRUE;
      break;
    case 'o':
      if ((outfp = fopen(optarg,"w")) == (FILE *)NULL) {
	fprintf(stderr, "%s: cannot open the file %s.\n", progname, optarg);
	exit(1);
      }
      break;
    case 'v':
      usage();
      exit(0);
      break;    /* Never reach */
    case '?':
    default:
      usage();
      exit(1);
    }
  }

  switch(argc - optind) {
  case 0:
    break;
  case 1:
    if ((infp = fopen(argv[optind],"r")) == (FILE *)NULL) {
      fprintf(stderr, "%s: %s -- No such file.\n", progname, argv[optind]);
      exit(1);
    }
    break;  /* Never reach */
  default:
    usage();
    exit(1);
  }

  /* データ読み込み */
  read_data(infp);
  /* データ初期化 */
  init_data();

  /* 入力データの表示 */
  if (debug_mode) print_data(board);

  if (ans_mode) {
    /* 求解モードなら解を求める．解は board_list に蓄えられる． */
    solve();
    if (board_list->next == NULL)
      /* 解は一つ */
      pretty_print_board(outfp, board_list->board, ans_mode, prog_readable_mode);
    else {
      /* 解が複数ある */
      i = 1;
      for(bl = board_list; bl != NULL; bl = bl->next) {
	fprintf(outfp, "No.%d\n", i++);
	pretty_print_board(outfp, bl->board, ans_mode, prog_readable_mode);
	fprintf(outfp, "\n\n");
      }
    }
  } else   /* 問題の表示 */
      pretty_print_board(outfp, board, ans_mode, prog_readable_mode);


  exit(0);
}


#define RETURN (-2)
#define NNMARK (-3)

/* データの読み込み */
void
read_data(FILE *fp)
{
  int c;
  struct area_data *newptr;
  int x = 0;
  int y = 0;

  while ((c = get_one_box(fp)) != EOF) {	/* 1マスのデータを読む */
    if (c >= 1) {				/* 数字ならデータ設定 */
      newptr = (struct area_data *)malloc(sizeof(struct area_data));
      newptr->sym 	= get_sym();
      newptr->x   	= x;
      newptr->y   	= y;
      newptr->extent	= c;
      newptr->tile	= (struct tile *)NULL;
      newptr->fixed	= FALSE;
      newptr->next	= area_data_ptr;

      area_data_ptr = newptr;
      x++;
    } else if (c == RETURN) {
      if (width <=0)
	width = x;
      else if (x != width && x != 0) {
	fprintf(stderr, "%s: malformed data (at line %d. %d != %d).\n", progname, y+1, x, width);
	exit(1);
      }
      if (x != 0) y++;
      x = 0;
    } else if (c == NNMARK) {
      x++;
    }
  }
  height = y;
}


/* コメント，区切り文字を読み飛ばし，1マス分のデータを読む．
 * 値 1〜9	その数字
 * 値 0		空欄
 */
int
get_one_box(FILE *fp)
{
  int c;
  int comment;

  do {
    comment = FALSE;
    c = getc(fp);
    if (c == '#') {
      comment = TRUE;
      while ((c = getc(fp)) != '\n' && c != EOF)
	;
    }
  } while (comment || !( ('0'<= c && c <= '9') || c == UNKNOWN || c == '\n' || c == EOF ));

  if ('0' <= c && c <= '9') {
    int num = 0;
    while ('0' <= c && c <= '9') {
      num = num*10 + c - '0';
      c = getc(fp);
    }
    ungetc(c,fp);
    c = num;
  } else if (c == UNKNOWN) {
    c = NNMARK;
  } else if (c == '\n') {
    c = RETURN;
  } else if ( c != EOF ) {
    c = FALSE;
  }

  return(c);
}


/* 内部データ用シンボル割り当て */
unsigned char
get_sym()
{
  static unsigned char sym = 0x20;

  if (sym == 0xff) {
    fprintf(stderr, "%s: no more symbols.\n", progname);
    exit(1);
  }
  sym++;

  if (sym == UNKNOWN || sym == MULTI)
    sym++;

  if (debug_mode) fprintf(stderr,"シンボル割り当て %c(%d)\n", sym, sym);
  return(sym);
}

/* データの初期化 */
void
init_data(void)
{
  int i,j;
  struct area_data *ad;

  board = alloc_board();
  old_board = alloc_board();
  org_board = alloc_board();
  work_board = alloc_board();

  for(ad = area_data_ptr; ad != NULL; ad = ad->next) {
    board[ad->y][ad->x] = ad->sym;
    org_board[ad->y][ad->x] = ad->extent;
    ad->tile = make_tiles(ad->x,ad->y,ad->extent);
  }
}

/* 盤面データの取得 */
unsigned char **
alloc_board(void)
{
  unsigned char **b;
  int i,j;

  b = (unsigned char **)malloc(sizeof(unsigned char *) * height);
  for (i=0; i<height; i++) {
    b[i] = (unsigned char *)malloc(sizeof(unsigned char)*width);
    for (j=0; j<width; j++) {
      b[i][j] = UNKNOWN;
    }
  }

  return(b);
}


/* 盤面データの解放 */
void
free_board(unsigned char **b)
{
  int i;

  for (i=0; i<height; i++)
    free(b[i]);
  free(b);
}


/* タイルデータの作成 */
struct tile *
make_tiles(int x, int y, int extent)
{
  int startx, starty, endx, endy, dx,dy;
  int i,j;
  struct tile *t = (struct tile *)NULL;
  struct tile *newt;

  for(dy=1; dy<=extent; dy++){
    dx=extent/dy;
    if (extent == dx*dy) {
      for (j=0; j<dy; j++) {
	for (i=0; i<dx; i++) {
	  startx = x - i;  starty = y - j;
	  endx = startx + dx -1; endy = starty + dy -1;
	  if (0 <= startx && endx < width &&
              0 <= starty && endy < height  ) {
	    newt = (struct tile *)malloc(sizeof(struct tile));
	    newt->sx = startx;	newt->sy = starty;
	    newt->ex = endx;	newt->ey = endy;
	    newt->valid = TRUE;	newt->next = t;
	    t = newt;
	  }
	}
      }
    }
  }

  return(t);
}


/* 求解 */
void
solve()
{
  struct area_data *ad,*newad, *ad1;
  struct tile *t, *newt, *t1;
  int x,y;
  int step_count = 0;

  do {
    copy_board(old_board, board, TRUE);
    /*
     * 現在のタイルに基づいてマークを付ける
     * 他のタイルと重なりがないのであれば，該当記号をマーク
     * 他のタイルと重なりがあるのであれば，MULTIをマーク
     */
    if (debug_mode) fprintf(stderr,"マーク付け...");
    for(ad = area_data_ptr; ad != NULL; ad = ad->next) {
      for(t = ad->tile; t != NULL; t = t->next) {
	for(y = t->sy; y <= t->ey; y++)
	  for(x = t->sx; x <= t->ex; x++)
	    if (board[y][x] == UNKNOWN)
	      board[y][x] = ad->sym;
	    else if (board[y][x] != ad->sym && old_board[y][x] == UNKNOWN)
	      board[y][x] = MULTI;
      }
    }

    /* MULTI を UNKNOWN になおす */
    clear_multi_mark(board);

    if (debug_mode) {
      fprintf(stderr, "done.\n");
      fprintf(stderr, "ボード情報\n");
      print_board(stderr, board);
    }

    /*
     *   以下のタイルを破棄する．
     *   (a) 該当シンボルの確定領域に関して，それを含まないタイル
     *   (b) 他の確定シンボルを含むタイル
     */
    if (debug_mode) fprintf(stderr, "不適なタイルの排除...");
    for(ad = area_data_ptr; ad != NULL; ad = ad->next) {
      for(t = ad->tile; t != NULL; t = t->next) {
	for(y = 0; y <height && t->valid; y++)
	  for(x = 0; x <width && t->valid; x++)
	    if (t->sx <= x && x <= t->ex && t->sy <= y && y <= t->ey) { /* タイル領域内 */
	      if (board[y][x] != ad->sym && board[y][x] != UNKNOWN && board[y][x] != MULTI)
		t->valid = FALSE;
	    } else {		/* タイル領域外 */
	      if (board[y][x] == ad->sym)
		t->valid = FALSE;
	    }
      }
      newt = (struct tile *)NULL;
      t = ad->tile;
      while(t != NULL) {
	t1 = t;
	t = t->next;
	if (t1->valid) {
	  t1->next = newt;
	  newt = t1;
	} else
	  free(t1);
      }
      ad->tile = newt;
    }

    if (debug_mode) {
      fprintf(stderr, "done.\n");
      print_data(board);
    }

    /*
     * 現在のタイルに基づいてマークを付ける
     * すべてのタイルに共通する領域はかならずマークされるので該当記号をマーク
     * また一つしかタイル候補がないときは確定
     */
    if (debug_mode) fprintf(stderr, "すべてのタイルの共通部分のマーク...");
    for(ad = area_data_ptr; ad != NULL; ad = ad->next) {
      set_unknown_mark(work_board);
      t = ad->tile;
      for(y = t->sy; y <= t->ey; y++)
	for(x = t->sx; x <= t->ex; x++)
	  work_board[y][x] = ad->sym;
      if (t->next == NULL) {	/* タイル候補が1つしかない場合は確定 */
	ad->fixed = TRUE;
	if (debug_mode) fprintf(stderr, "\nタイルの確定 for symbole %c(%d)\n", ad->sym,ad->sym);
      } else
	for(t = t->next; t != NULL; t = t->next)
	  for(y = 0; y <height; y++)
	    for(x = 0; x <width; x++)
	      if (x < t->sx || x > t->ex || y < t->sy || y > t->ey)
		work_board[y][x] = UNKNOWN;
      if (debug_mode) {
	fprintf(stderr, "\n");
	print_board(stderr, work_board);
	fprintf(stderr, "\n");
      }
      copy_board(board, work_board, FALSE);
    }

    /* 確定したものの削除 */
    newad = NULL;
    while(area_data_ptr != NULL) {
      ad1 = area_data_ptr;
      area_data_ptr = area_data_ptr->next;
      if (ad1->fixed)
	free(ad1);
      else {
	ad1->next = newad;
	newad = ad1;
      }
    }
    area_data_ptr = newad;

    if (debug_mode) {
      fprintf(stderr, "done.\n");
      step_count++;
      fprintf(stderr, "ボード情報(%d ステップ目)\n", step_count);
      print_board(stderr, board);
    }
  } while (area_data_ptr != NULL && different_board(board,old_board));
  /* 領域データがすべて確定するか，盤面が変わらなくなるまで繰り返す */

  
  if (area_data_ptr != NULL) {
    /* 領域データが残った場合は，両立可能なタイルを全解探索 */
    if (debug_mode) {
      fprintf(stderr, "探索モード...");
    }
    board_list = NULL;
    search_answers(NULL,area_data_ptr);
    if (debug_mode) {
      fprintf(stderr, "done.\n");
    }
  } else {
    board_list = (struct board_list *)malloc(sizeof(struct board_list));
    board_list->board = board;
    board_list->next = NULL;
  }
}


void
search_answers(unsigned char **b, struct area_data *ad)
{
  struct tile *t;
  unsigned char **newb;
  struct board_list *newbl;
  int x,y,ok;

  if (b==NULL) b = alloc_board();

  newb = alloc_board();
  copy_board(newb,b,TRUE);

  for (t=ad->tile; t != NULL; t=t->next) {
    ok = TRUE;
    for(y = t->sy; y <= t->ey && ok ; y++)
      for(x = t->sx; x <= t->ex && ok ; x++)
	if (newb[y][x] == UNKNOWN)
	  newb[y][x] = ad->sym;
	else
	  ok = FALSE;
    if (ok) {
      if (ad->next != NULL)
	search_answers(newb, ad->next);
      else {
	newbl = (struct board_list *)malloc(sizeof(struct board_list));
	newbl->board = alloc_board();
	copy_board(newbl->board,newb,FALSE);
	copy_board(newbl->board,board,FALSE);
	newbl->next = board_list;
	board_list = newbl;
      }
    }
    copy_board(newb,b,TRUE);
  }
  free(newb);
}



/* 盤面データの複写 */
void
copy_board(unsigned char **dest, unsigned char **src, int copy_unknown)
{
  int i,j;

  for(j=0; j<height; j++)
    for(i=0; i<width; i++)
      if (copy_unknown || src[j][i] != UNKNOWN)
	dest[j][i] = src[j][i];
}

/* MULTI マークを UNKNOWN マーク につけかえる．*/
void
clear_multi_mark(unsigned char **b)
{
  int i,j;

  for(j=0; j<height; j++)
    for(i=0; i<width; i++)
      if (b[j][i] == MULTI) b[j][i] = UNKNOWN;
}

/* UNKNOWN マーク でうめる */
void
set_unknown_mark(unsigned char **b)
{
  int i,j;

  for(j=0; j<height; j++)
    for(i=0; i<width; i++)
      b[j][i] = UNKNOWN;
}

/*
 *  二つの盤面データの同値性を調べる
 *  違う時に真になる
 */
different_board(unsigned char **b1, unsigned char **b2)
{
  int i,j;

  for(j=0; j<height; j++)
    for(i=0; i<width; i++)
      if (b1[j][i] != b2[j][i]) return(TRUE);

  return(FALSE);
}

/* 盤面データの表示 */
void
print_board(FILE *fp, unsigned char **b)
{
  int i,j;

  for (j=0; j<height; j++) {
    for (i=0; i<width; i++)
      fprintf(fp," %c", b[j][i]);
    fprintf(fp,"\n");
  }
}

/*
 * 解を清書する．
 *   print_ans
 *     TRUE ならば 解表示, FALSE ならば 問題表示
 *   prog_readable
 *     TRUE ならば このプログラムで読める表示形式になる．
 *     FALSE ならば 人間が読みやすい表示形式になる．
 */
void
pretty_print_board(FILE *fp, unsigned char **b, int print_ans, int prog_readable)
{
  int i,j;

  fprintf(fp,"+");
  for (i=0; i<width; i++) 
    fprintf(fp, "---+");
  fprintf(fp,"\n");

  for (j=0; j<height; j++) {
    fprintf(fp,"|");
    for (i=0; i<width; i++) {
      if (org_board[j][i] == UNKNOWN) {
	if (prog_readable)
	  fprintf(fp, " %c ", UNKNOWN);
	else
	  fprintf(fp, "   ");
      } else
	fprintf(fp, "%2d ", org_board[j][i]);
      if (i == (width -1) || print_ans && b[j][i] != b[j][i+1])
	fprintf(fp,"|");
      else
	fprintf(fp," ");
    }
    fprintf(fp,"\n");
    fprintf(fp,"+");
    for (i=0; i<width; i++) {
      if (j == (height -1) || print_ans && b[j][i] != b[j+1][i])
	fprintf(fp,"---+");
      else
	fprintf(fp,"   +");
    }
    fprintf(fp,"\n");
  }
}

/* 内部データの表示 */
void
print_data(unsigned char **b)
{
  int i,j;
  struct area_data *ad;
  struct tile *t;

  ad = area_data_ptr;

  for(; ad != NULL; ad = ad->next) {
    fprintf(stderr, "\n領域データ for symbol %c(%d) ----- (%d,%d), 広さ:%d, fixed:%s\n",
            ad->sym, ad->sym, ad->x, ad->y, ad->extent, (ad->fixed)?"true":"false");
    t = ad->tile;
    for(; t != NULL; t = t->next) {
      fprintf(stderr, "  タイルデータ --- (%d,%d)-(%d,%d), valid:%s\n",
	      t->sx, t->sy, t->ex, t->ey, (t->valid)?"true":"false");
    }
  }

  fprintf(stderr, "\nボード情報\n");
  print_board(stderr, b);
}

/* 使い方を表示する */
void
usage(void)
{
  char *rev = "$Revision: 1.6 $";
  char *ver;

  ver = malloc((unsigned)strlen(rev)-9);
  sscanf(&(rev[1]), "Revision: %s", ver);
  fprintf(stderr, "「四角に切れ」解法プログラム Ver. %s\n",ver);
  fprintf(stderr, "     Copyright (c) 1995  by T.Mori\n\n");
  fprintf(stderr, "【使い方】\n");
  fprintf(stderr,
	  "%s [-d] [-r] [-p] [-o 出力ファイル名] [-v] [データファイル名]\n\n",
	  progname);
  fprintf(stderr,
	  "      -d                 :  途中結果も表示するデバッグモード (off)\n");
  fprintf(stderr,
	  "      -r                 :  プログラム可読出力モード (off)\n");
  fprintf(stderr,
	  "      -p                 :  問題清書モード．解を求めない (off)\n");
  fprintf(stderr,
	  "      -o 出力ファイル名  :  出力ファイルの名前 (標準出力)\n");
  fprintf(stderr,
	  "      -v                 : バージョンの表示\n");
  fprintf(stderr,
	  "      データファイル名   : データファイルの名前 (標準入力)\n");
  fprintf(stderr,
	  "                                  (括弧内は省略時の値)\n");
}

/******************************************************************************

	プログラム記述終了

 ******************************************************************************/
