Go: package main

import "fmt"

var H, W int

type point struct {
	x, y int
}

func (p *point) add(q point) {
	p.x += q.x
	p.y += q.y
	if p.x < 0 {
		p.x += H
	}
	if p.y < 0 {
		p.y += W
	}
	p.x %= H
	p.y %= W
}

func isPalindrome(str string) bool {
	for i, j := 0, len(str)-1; i < j; i, j = i+1, j-1 {
		if str[i] != str[j] {
			return false
		}
	}
	return true
}

func magicSpel(arr []string) string {
	var ans string
	m := map[string]int{}
	for i := range arr {
		for j := range arr[i] {
			for _, d := range []point{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}} {
				cur := point{x: i, y: j}
				str := string(arr[cur.x][cur.y])
				cur.add(d)
				for i != cur.x || j != cur.y {
					str += string(arr[cur.x][cur.y])
					cur.add(d)
					if isPalindrome(str) {
						m[str] += 2
					} else {
						m[str]++
					}
				}
			}
		}
	}
	for s, v := range m {
		if 1 < v {
			if len(ans) < len(s) {
				ans = s
			} else if len(ans) == len(s) && s < ans {
				ans = s
			}
		}
	}

	if len(ans) == 0 {
		return "0"
	}

	return ans
}

func main() {
	for {
		fmt.Scan(&H, &W)
		if H == 0 && W == 0 {
			break
		}

		var arr []string

		for i := 0; i < H; i++ {
			var s string
			fmt.Scan(&s)
			arr = append(arr, s)
		}

		fmt.Println(magicSpel(arr))
	}
}

// 2 3
// ABC
// DEF

C++: #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}

map<string,int> mp;

int h,w;
char fi[22][22];

int dx[]={1,1,1,0,0,-1,-1,-1};
int dy[]={-1,0,1,-1,1,-1,0,1};

void dfs(int sx,int sy,int x,int y,int k,string s){
	s+=fi[x][y];
	mp[s]++;
	int nx=(x+dx[k]+h)%h;
	int ny=(y+dy[k]+w)%w;
	if(nx==sx&&ny==sy)return;
	dfs(sx,sy,nx,ny,k,s);
}

int main(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	while(cin >> h >> w,h){
		mp.clear();
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				cin >> fi[i][j];
			}
		}
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				for(int k=0;k<8;k++){
					dfs(i,j,i,j,k,"");
				}
			}
		}
		string res="";
		for(auto p:mp){
			if(p.second>=2){
				if(p.first.size()>res.size())res=p.first;
				else if(p.first.size()==res.size())res=min(res,p.first);
			}
		}
		cout << ((res.size()>=2)?res:"0") << endl;
	}
}

C++: #include <bits/stdc++.h>
using namespace std;

//#define int long long
#define reps(i,s,n) for(int (i)=(s);(i)<(n);++(i))
#define rep(i,n) reps(i,0,n)
#define rept(i,n) rep(i,(n)+1)
#define repst(i,s,n) reps(i,s,(n)+1)
#define reprt(i,n,t) for(int (i)=(n);(i)>=(t);--(i))
#define repr(i,n) reprt(i,n,0)
#define each(itr,v) for(auto (itr):(v))
#define all(c) (c).begin(),(c).end()
#define rall(c) (c).rbegin(),(c).rend()
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define tmax(x,y,z) max(x,max(y,z))
#define tmin(x,y,z) min(x,min(y,z))
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
#define ln '\n'
#define bln(i,n) (((i)==(n)-1)?'\n':' ')
#define dbg(x) cout<<#x" = "<<(x)<<ln<<flush
#define dbga(x,n) {cout<<#x" : ";for(int (i)=0;i<(n);++i){cout<<((x)[i])<<(i==((n)-1)?'\n':' ')<<flush;}}
#define zero(a) memset(a,0,sizeof(a))
#define unq(a) sort(all(a)),a.erase(unique(all(a)),a.end())

typedef complex<double> P;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<string> vst;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vector<int> > mat;

const ll inf = (ll)1e9+10;
const ll linf = (ll)1e18+10;
const ll mod = (ll)(1e9+7);
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
const int ddx[] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[] = {1, 1, 0, -1, -1, -1, 0, 1};
const double eps = 1e-10;

ll mop(ll a,ll b,ll m=mod) {ll r=1;a%=m;for(;b;b>>=1){if(b&1)r=r*a%m;a=a*a%m;}return r;}
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b) {return a*b/gcd(a,b);}
bool ool(int x,int y,int h,int w) {return((x<0)||(h<=x)||(y<0)||(w<=y));}
bool deq(double a,double b) {return abs(a-b)<eps;}

struct oreno_initializer {
	oreno_initializer() {
		cin.tie(0);
		ios::sync_with_stdio(0);
	}
} oreno_initializer;

// ━━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…
// .｡.:( ^ω^)・ﾟ＋.｡.:( ^ω^)・ﾟ＋.｡.:( ^ω^)・ﾟ＋.｡.:( ^ω^)・ﾟ＋.｡.:( ^ω^)・ﾟ＋
// ・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・‥…━━━☆・

int h, w;
string s[10];

signed main() {
	while (1) {
		cin >> h >> w;
		if (h==0) break;
		rep(i,h) cin >> s[i];
		map<string,int> m;
		rep(i,h) rep(j,w) {
			int ii = i, jj = j;
			rep(k,8) {
				string t;
				t.pb(s[i][j]);
				while (1) {
					ii += ddx[k]+h, jj += ddy[k]+w;
					ii %= h, jj %= w;
					if (ii==i && jj==j) break;
					t.pb(s[ii][jj]);
					m[t]++;
				}
			}
		}
		string res;
		each(i,m) if (i.se>=2 && (res.size()<i.fi.size() || (res.size()==i.fi.size() && res>i.fi))) res = i.fi;
		if (res.empty()) cout << 0 << ln;
		else cout << res << ln;
	}
}

C++: #include <iostream>
#include <algorithm>
#include <string>
#include <set>
using namespace std;
 
const int dy[8] = {1,1,1,0,0,-1,-1,-1};
const int dx[8] = {-1,0,1,-1,1,-1,0,1};
 
int h,w;
string str[10];
 
void solve(){
  int y, x, ansn = 0;
  string ans = "0", st;
  set<string> s;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      for(int k=0;k<8;k++){
        st.clear();
        st += str[i][j];
        y = i;
        x = j;
        while(1){
          y = (y + h + dy[k]) % h;
          x = (x + w + dx[k]) % w;
          if(y == i && j == x) break;
          else st += str[y][x];
          if(!s.empty() && s.find(st) != s.end()){
            if(ansn < st.size() || ansn == st.size() && ans > st){
              ans = st;
              ansn = st.size();
            }
          } else if(st.size() >= ansn) s.insert(st);
        }
 
      }
    }
  }
  cout << ans << endl;
}
 
int main(){
  while(cin >> h >> w && (h|w)){
    for(int i=0;i<h;i++){
      cin >> str[i];
    }
    solve();
  }
}

C++: #include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <cstring>
#include <functional>
#include <cmath>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
#define rep1(i,n) for(int i=1;i<=(n);++i)
#define all(c) (c).begin(),(c).end()
#define fs first
#define sc second
#define pb push_back
#define show(x) cout << #x << " " << x << endl
int dx[8]={1,-1,0,0,1,1,-1,-1},dy[8]={0,0,1,-1,1,-1,1,-1};
void renew(string &x,string y){
	if(x.size()>y.size()) return;
	if(x.size()<y.size()){
		x=y;
		return;
	}
	if(x>y) x=y;
}
int main(){
	while(true){
		int H,W;
		cin>>H>>W;
		if(H==0) break;
		string s[10];
		rep(i,H) cin>>s[i];
		string ans;
		rep(ai,H) rep(aj,W) rep(ad,8){
			//show(ai);
			//show(aj);
			//show(ad);
			string sa;
			int ax=ai,ay=aj;
			do{
				sa+=s[ax][ay];
				ax+=dx[ad],ay+=dy[ad];
				if(ax==H) ax=0;
				if(ay==W) ay=0;
				if(ax==-1) ax=H-1;
				if(ay==-1) ay=W-1;
				//show(ax);
				//show(ay);
			}while(!(ax==ai&&ay==aj));
			//show(sa);
			rep(bi,H) rep(bj,W) rep(bd,8){
				if(ai==bi&&aj==bj&&ad==bd) continue;
				//show(bi);
				//show(bj);
				//show(bd);
				string sb;
				int bx=bi,by=bj;
				do{
					//show(bx);
					//show(by);
					sb+=s[bx][by];
					bx+=dx[bd],by+=dy[bd];
					if(bx==H) bx=0;
					if(by==W) by=0;
					if(bx==-1) bx=H-1;
					if(by==-1) by=W-1;
				}while(!(bx==bi&&by==bj));
				//show(sb);
				int u=min(sa.size(),sb.size())+1,l=0;
				while(u-l>1){
					int m=(u+l)/2;
					if(sa.substr(0,m)==sb.substr(0,m)) l=m;
					else u=m;
				}
				renew(ans,sb.substr(0,l));
			}
		}
		if(ans.size()<=1) puts("0");
		else cout<<ans<<endl;
	}
}