Problem:
Problem B: The Sorcerer's Donut

Your master went to the town for a day. You could have a relaxed day without hearing his
scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he
can't live without eating tens of donuts everyday. What a chore for such a beautiful day.

But last week, you overheard a magic spell that your master was using. It was the time to
try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of
lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he
brought flour from the storage, and started kneading dough. The spell worked, and how fast he
kneaded it!

A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for
the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the
spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he
still worked as fast as he could. If you could not stop him now, you would be choked in the
kitchen filled with pieces of dough.

Wait, didn't your master write his spells on his notebooks? You went to his den, and found the
notebook that recorded the spell of cessation.

But it was not the end of the story. The spell written in the notebook is not easily read by
others. He used a plastic model of a donut as a notebook for recording the spell. He split the
surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters
(Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless.
But you knew that he wrote the pattern so that the spell "appears" more than once (see the next
paragraph for the precise conditions). The spell was not necessarily written in the left-to-right
direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up,
and the 4 diagonal directions.

You should be able to find the spell as the longest string that appears more than once. Here,
a string is considered to appear more than once if there are square sequences having the string
on the donut that satisfy the following conditions.

Each square sequence does not overlap itself. (Two square sequences can share some squares.)

The square sequences start from different squares, and/or go to different directions.

Figure B.1: The Sorcerer's Donut Before
Filled with Letters, Showing the Mesh and 8
Possible Spell Directions

Figure B.2: The Sorcerer's Donut After Filled
with Letters

Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards)
that satisfies the first condition "appears" twice.

The pattern on the donut is given as a matrix of letters as follows.

ABCD
EFGH
IJKL

Note that the surface of the donut has no ends; the top and bottom sides, and the left and right
sides of the pattern are respectively connected. There can be square sequences longer than both
the vertical and horizontal lengths of the pattern. For example, from the letter F in the above
pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are
as follows.

FGHE
FKDEJCHIBGLA
FJB
FIDGJAHKBELC
FEHG
FALGBIHCJEDK
FBJ
FCLEBKHAJGDI

Please write a program that finds the magic spell before you will be choked with pieces of donuts
dough.

Input

The input is a sequence of datasets. Each dataset begins with a line of two integers h and w,
which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z,
inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20.

The end of the input is indicated by a line containing two zeros.

Output

For each dataset, output the magic spell. If there is more than one longest string of the same
length, the first one in the dictionary order must be the spell. The spell is known to be at least
two letters long. When no spell is found, output 0 (zero).

Sample Input

5 7
RRCABXT
AABMFAB
RROMJAC
APTADAB
YABADAO
3 13
ABCDEFGHIJKLM
XMADAMIMADAMY
ACEGIKMOQSUWY
3 4
DEFG
ACAB
HIJK
3 6
ABCDEF
GHIAKL
MNOPQR
10 19
JFZODYDXMZZPEYTRNCW
XVGHPOKEYNZTQFZJKOD
EYEHHQKHFZOVNRGOOLP
QFZOIHRQMGHPNISHXOC
DRGILJHSQEHHQLYTILL
NCSHQMKHTZZIHRPAUJA
NCCTINCLAUTFJHSZBVK
LPBAUJIUMBVQYKHTZCW
XMYHBVKUGNCWTLLAUID
EYNDCCWLEOODXYUMBVN
0 0

Output for the Sample Input

ABRACADABRA
MADAMIMADAM
ABAC
0
ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ

Solution in C (judge verdict: Runtime Error)

#include <stdio.h>
#include <string.h>
#define HASHTABLE_SIZE 40000
#define SPELL_LENGTH 191
#define NULL_INDEX -1

/* グループ */
typedef struct {
	char value[SPELL_LENGTH + 1];
	int length;
	int number;
} Item;

Item hashtable[HASHTABLE_SIZE]; /* 配列から取り出せる全ての文字列 */
int bottomlength;

/* 文字列のハッシュ値を求める */
int hash(const char* s) {
	int i, h = 0, a = 3141, b = 2718;
	for (i = 0; s[i] != '\0'; i++, a = a * b % (HASHTABLE_SIZE - 1)) h = (a * h + s[i]) % HASHTABLE_SIZE;
	return h;
}

/* ハッシュ表を初期化する */
void init() {
	int i;
	bottomlength = 2;
	for (i = 0; i < HASHTABLE_SIZE; i++) {
		hashtable[i].length = 0;
		hashtable[i].number = 0;
	}
}

/* 指定された呪文の番号を返す */
int searchH(const char* s, int h) {
	int i;
	for (i = hash(s); hashtable[i].number != 0; i++) {
		if (strcmp(s, hashtable[i].value) == 0) return i;
	}
	return NULL_INDEX;
}
int search(const char* s) {
	return searchH(s, hash(s));
}

/* 指定された呪文を配列に追加し呪文に割り当てられた番号を返す */
int add(const char* s) {
	int h = hash(s);
	int i = searchH(s, h);
	if (i == NULL_INDEX) {
		for (i = h; hashtable[i].length >= bottomlength; i++); /* 挿入可能な場所を探す */
		/* 新しい呪文を追加する */
		hashtable[i].number = 0;
		hashtable[i].length = strlen(s);
		strncpy(hashtable[i].value, s, hashtable[i].length + 1);
	}
	hashtable[i].number++; /* 同じ呪文の追加回数を数える */
	return i;
}

int VECTOR[8][2] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};

int main(void) {
	int h, w; /* 文字配列の大きさ */
	char data[10][20];
	int i, j, k;

	/* データセット毎の処理 */
	while (scanf("%d%d\n", &h, &w) == 2 && h >= 3 && h <= 10 && w >= 3 && w <= 20) {
		/* 文字配列を読み込む */
		for (i = 0; i < h; i++) for (j = 0; j < w; j++) {
			scanf("%c\n", &data[i][j]);
		}

		init(); /* 初期化 */

		/* 配列から取り出せる全ての文字列を探索する */
		int answer = NULL_INDEX;
		for (i = 0; i < h; i++) for (j = 0; j < w; j++) /* 始点 */ for (k = 0; k < 8; k++) /* 方向 */ {
			int used[10*20] = {}; /* 配列中のある文字を使ったか */
			int y = i, x = j; /* 現在の参照位置 */
			char s[SPELL_LENGTH] = {}; /* 取り出した文字列 */
			int sl; /* 長さ */
			for (sl = 1; used[w*y+x] == 0; sl++, y = (h + y + VECTOR[k][0]) % h, x = (w + x + VECTOR[k][1]) % w) {
				used[w*y+x] = 1;
				s[sl-1] = data[y][x]; /* 1文字加える */
				/* 文字列が呪文か判定する */
				/* if (sl > 1 || (answer != NULL_INDEX && sl >= hashtable[answer].length)) { */
				if (sl >= bottomlength) {
					int index = add(s);
					/* 同じ文字列が2回以上出現しているときこの文字列を呪文の候補とする */
					if (hashtable[index].number >= 2) {
						if (answer == NULL_INDEX) {
							answer = index; /* 初めて見つけた呪文候補 */
						} else {
							/* 最も長く辞書順で若い文字列を呪文とする */
							if (hashtable[index].length > hashtable[answer].length || (hashtable[index].length == hashtable[answer].length && strcmp(hashtable[index].value, hashtable[answer].value) < 0)) {
								answer = index;
							}
						}
						bottomlength = sl;
					}
				}
			}
		}

		/* 出力 */
		if (answer == NULL_INDEX) printf("0\n");
		else printf("%s\n", hashtable[answer].value);
	}

	return 0;
}