puwaer/puwaer_code_translation huggingface dataset:
AtCoder problem 067

C++ solution:




Rust solution: use proconio::{input,marker::Chars};
fn main() {
	input!{
		(n, k): (Chars, usize)
	}
	let mut s = Vec::new();
	for c in n.clone().into_iter().rev() {
		s.push(c.to_string().parse::<isize>().unwrap());
	}
	for _ in 0..k {
		let mut ans = 0;
		for (i,d) in s.clone().into_iter().enumerate() {
			let p:isize = 8_isize.pow(i as u32);
			ans += d*p;
		}
		s = Vec::new();
		while ans/9>0 {
			s.push(if ans%9==8 {5} else {ans%9});
			ans /= 9;
		}
		s.push(if ans%9==8 {5} else {ans%9});
	}
	s.iter().rev().for_each(|i|print!("{}",i));
	println!("");
}


Ruby solution: n, k = readline.chomp.split
k.to_i.times do
    n = n.to_i(8).to_s(9).tr('8', '5')
end
puts n
AtCoder problem 069

C++ solution:
#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

const int mod = 1000000007;

int binpower(int a, long long b) {

	int ans = 1;

	while (b != 0) {

		if (b % 2 == 1) {

			ans = (long long)(ans)*a % mod;

		}

		a = (long long)(a)*a % mod;

		b /= 2;

	}

	return ans;

}

int main() {

	long long N; int K;

	cin >> N >> K;

	if (K == 1) {

		cout << (N == 1 ? 1 : 0) << endl;

	}

	else if (N == 1) {

		cout << K % mod << endl;

	}

	else if (N == 2) {

		cout << (long long)(K) * (K - 1) % mod << endl;

	}

	else {

		cout << (long long)(K) * (K - 1) % mod * binpower(K - 2, N - 2) % mod << endl;

	}

	return 0;

}

Crystal solution: struct Int
  def pow(exp : Int, mod : Int)
    t, result = self, typeof(self).new(1)
    while exp > 0
      result = result * t % MOD if exp.odd?
      t = t * t % MOD
      exp >>= 1
    end
    result
  end
end

MOD = 10**9 + 7
n, k = read_line.split.map(&.to_i64)
ans = k
if n >= 2
  ans = ans * (k - 1) % MOD
  ans = ans * (k - 2).pow(n - 2, MOD) % MOD
end
puts ans
AtCoder problem 069

C++ solution:
#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

const int mod = 1000000007;

int binpower(int a, long long b) {

	int ans = 1;

	while (b != 0) {

		if (b % 2 == 1) {

			ans = (long long)(ans)*a % mod;

		}

		a = (long long)(a)*a % mod;

		b /= 2;

	}

	return ans;

}

int main() {

	long long N; int K;

	cin >> N >> K;

	if (K == 1) {

		cout << (N == 1 ? 1 : 0) << endl;

	}

	else if (N == 1) {

		cout << K % mod << endl;

	}

	else if (N == 2) {

		cout << (long long)(K) * (K - 1) % mod << endl;

	}

	else {

		cout << (long long)(K) * (K - 1) % mod * binpower(K - 2, N - 2) % mod << endl;

	}

	return 0;

}





Kuin solution: func main()
	var n: int :: cui@inputInt()
	var k: int :: cui@inputInt()
	
	const mod: int :: 1000000007
	var ans: int :: 0
	
	switch(n)
	case 1
		do ans :: k
	case 2
		if(k < 2)
			do ans :: 0
		else
			do ans :: k * (k - 1) % mod
		end if
	default
		if(k < 3)
			do ans :: 0
		else
			do ans :: k * (k - 1) % mod * (math@modPow(k - 2, n - 2, mod) % mod) % mod
		end if
	end switch
	do cui@print("\{ans}\n")
end func
AtCoder problem 069

C++ solution:

Crystal solution: struct Int
  def pow(exp : Int, mod : Int)
    t, result = self, typeof(self).new(1)
    while exp > 0
      result = result * t % MOD if exp.odd?
      t = t * t % MOD
      exp >>= 1
    end
    result
  end
end

MOD = 10**9 + 7
n, k = read_line.split.map(&.to_i64)
ans = k
if n >= 2
  ans = ans * (k - 1) % MOD
  ans = ans * (k - 2).pow(n - 2, MOD) % MOD
end
puts ans





Kuin solution: func main()
	var n: int :: cui@inputInt()
	var k: int :: cui@inputInt()
	
	const mod: int :: 1000000007
	var ans: int :: 0
	
	switch(n)
	case 1
		do ans :: k
	case 2
		if(k < 2)
			do ans :: 0
		else
			do ans :: k * (k - 1) % mod
		end if
	default
		if(k < 3)
			do ans :: 0
		else
			do ans :: k * (k - 1) % mod * (math@modPow(k - 2, n - 2, mod) % mod) % mod
		end if
	end switch
	do cui@print("\{ans}\n")
end func
AtCoder problem 070

C++ solution:
#include <bits/stdc++.h>

#include <atcoder/all>

#include <string>



#define rep(i,n) for(int i=0;i < (n);i++)

#define rep2(i, s, n) for (int i = (s); i < (n); i++)

#define rrep(i,n) for(int i=n-1;i>=0;i--)

#define ff first

#define ss second

#define pb push_back

#define ALL(a) (a).begin(),(a).end()



typedef long long ll;



const ll MOD=1000000007ll;

const int MAX=5100000;



using namespace std;

using namespace atcoder;

using mint = modint1000000007;



// aよりもbが大きいならばaをbで更新する

// (更新されたならばtrueを返す)

template <typename T>

bool chmax(T &a, const T& b) {

  if (a < b) {

    a = b;  // aをbで更新

    return true;

  }

  return false;

}

// aよりもbが小さいならばaをbで更新する

// (更新されたならばtrueを返す)

template <typename T>

bool chmin(T &a, const T& b) {

  if (a > b) {

    a = b;  // aをbで更新

    return true;

  }

  return false;

}



ll i,j,k;



int main()

{

	cin.tie(0);	ios::sync_with_stdio(false);

	ll N; cin >> N;

	vector<ll> X(N), Y(N);

	rep(i, N){cin >> X.at(i) >> Y.at(i);}

	sort(ALL(X));

	sort(ALL(Y));



	// xとyで個別に計算

	// x座標の候補：X[0]～X[N-1]のN通り

	ll ansx, ansy, tmpx, tmpy;

	tmpx = 0; tmpy = 0;

	// a=X[0]としたときの不便さを計算

	rep(i, N){tmpx += X[i] - X[0]; tmpy += Y[i] - Y[0];}

	ansx = tmpx; ansy = tmpy;

	// i=1からN-1まで、差分更新しながら計算

	for(i=1; i<N; i++){

		// i以下の座標：不便さがX[i]-X[i-1]増える

		// i+1以上の座標：不便さがX[i]-X[i-1]減る

		tmpx -= (N - i) * (X[i] - X[i-1]);

		tmpx += i * (X[i] - X[i-1]);

		chmin(ansx, tmpx);

		tmpy -= (N - i) * (Y[i] - Y[i-1]);

		tmpy += i * (Y[i] - Y[i-1]);

		chmin(ansy, tmpy);

	}



	cout << ansx + ansy << endl;



  return 0;

}



Crystal solution: n = read_line.to_i
puts (1..n).map {
  read_line.split.map(&.to_i64)
}.transpose.sum { |a|
  x = a.sort[n // 2]
  a.sum { |y| (x - y).abs }
}
AtCoder problem 070

C++ solution:
#include <bits/stdc++.h>

#include <atcoder/all>

#include <string>



#define rep(i,n) for(int i=0;i < (n);i++)

#define rep2(i, s, n) for (int i = (s); i < (n); i++)

#define rrep(i,n) for(int i=n-1;i>=0;i--)

#define ff first

#define ss second

#define pb push_back

#define ALL(a) (a).begin(),(a).end()



typedef long long ll;



const ll MOD=1000000007ll;

const int MAX=5100000;



using namespace std;

using namespace atcoder;

using mint = modint1000000007;



// aよりもbが大きいならばaをbで更新する

// (更新されたならばtrueを返す)

template <typename T>

bool chmax(T &a, const T& b) {

  if (a < b) {

    a = b;  // aをbで更新

    return true;

  }

  return false;

}

// aよりもbが小さいならばaをbで更新する

// (更新されたならばtrueを返す)

template <typename T>

bool chmin(T &a, const T& b) {

  if (a > b) {

    a = b;  // aをbで更新

    return true;

  }

  return false;

}



ll i,j,k;



int main()

{

	cin.tie(0);	ios::sync_with_stdio(false);

	ll N; cin >> N;

	vector<ll> X(N), Y(N);

	rep(i, N){cin >> X.at(i) >> Y.at(i);}

	sort(ALL(X));

	sort(ALL(Y));



	// xとyで個別に計算

	// x座標の候補：X[0]～X[N-1]のN通り

	ll ansx, ansy, tmpx, tmpy;

	tmpx = 0; tmpy = 0;

	// a=X[0]としたときの不便さを計算

	rep(i, N){tmpx += X[i] - X[0]; tmpy += Y[i] - Y[0];}

	ansx = tmpx; ansy = tmpy;

	// i=1からN-1まで、差分更新しながら計算

	for(i=1; i<N; i++){

		// i以下の座標：不便さがX[i]-X[i-1]増える

		// i+1以上の座標：不便さがX[i]-X[i-1]減る

		tmpx -= (N - i) * (X[i] - X[i-1]);

		tmpx += i * (X[i] - X[i-1]);

		chmin(ansx, tmpx);

		tmpy -= (N - i) * (Y[i] - Y[i-1]);

		tmpy += i * (Y[i] - Y[i-1]);

		chmin(ansy, tmpy);

	}



	cout << ansx + ansy << endl;



  return 0;

}







Kuin solution: func main()
	var n: int :: cui@inputInt()
	var x: []int :: #[n]int
	var y: []int :: #[n]int
	for i(0, n - 1)
		do x[i] :: cui@inputInt()
		do y[i] :: cui@inputInt()
	end for
	do x.sort()
	do y.sort()
	
	var ans: int :: 0
	for i(0, n - 1)
		do ans :+ (x[i] - x[n / 2]).abs()
		do ans :+ (y[i] - y[n / 2]).abs()
	end for
	do cui@print("\{ans}\n")
end func
AtCoder problem 070

C++ solution:

Crystal solution: n = read_line.to_i
puts (1..n).map {
  read_line.split.map(&.to_i64)
}.transpose.sum { |a|
  x = a.sort[n // 2]
  a.sum { |y| (x - y).abs }
}


Python solution: class INPUT:
  def __init__(self):
    self._l=open(0).read().split()
    self._length=len(self._l)
    self._index=0
    return

  def stream(self,k=1,f=int,f2=False):
    assert(-1<k)
    if self._length==self._index or self._length-self._index<k:
      raise Exception("There is no input!")
    elif f!=str:
      if k==0:
        ret=list(map(f,self._l[self._index:]))
        self._index=self._length
        return ret
      if k==1 and not f2:
        ret=f(self._l[self._index])
        self._index+=1
        return ret
      if k==1 and f2:
        ret=[f(self._l[self._index])]
        self._index+=1
        return ret
      ret=[]
      for _ in [0]*k:
        ret.append(f(self._l[self._index]))
        self._index+=1
      return ret
    else:
      if k==0:
        ret=list(self._l[self._index:])
        self._index=self._length
        return ret
      if k==1 and not f2:
        ret=self._l[self._index]
        self._index+=1
        return ret
      if k==1 and f2:
        ret=[self._l[self._index]]
        self._index+=1
        return ret
      ret=[]
      for _ in [0]*k:
        ret.append(self._l[self._index])
        self._index+=1
      return ret
pin=INPUT().stream

"""
pin(number[default:1],f[default:int],f2[default:False])
if number==0 -> return left all
listを変数で受け取るとき、必ずlistをTrueにすること。
"""

def main():
  N=pin(1)
  X=[]
  Y=[]
  for _ in[0]*N:
    x,y=pin(2)
    X.append(x)
    Y.append(y)
  X.sort()
  Y.sort()
  ac=-10**9-10
  wa=10**9+10
  #3分探索
  ansx=float("inf")
  searchX=lambda c:sum(abs(c-i)for i in X)
  for _ in[0]*100:
    #print(ac,wa)
    midx1=(2*ac+wa)//3
    midx2=(ac+2*wa)//3
    d1=searchX(midx1)
    d2=searchX(midx2)
    if d1<d2:
      wa=midx2
    else:
      ac=midx1
  ansx=ac
  if searchX(ac)>searchX(wa):
    ansx=wa
  if searchX(wa)>searchX((ac+wa)//2):
    ansx=(wa+ac)//2
  #print(ansx)
  ac=-10**9-10
  wa=10**+10
  searchY=lambda c:sum(abs(c-i)for i in Y)
  for _ in[0]*100:
    #print(ac,wa)
    midy1=(2*ac+wa)//3
    midy2=(ac+2*wa)//3
    d1=searchY(midy1)
    d2=searchY(midy2)
    if d1<d2:
      wa=midy2
    else:
      ac=midy1
  ansy=ac
  if searchY(ac)>searchY(wa):
    ansy=wa
  if searchY(wa)>searchY((ac+wa)//2):
    ansy=(wa+ac)//2
  #print(ansy)
  print(searchX(ansx)+searchY(ansy))
  return

main()
AtCoder problem 070

C++ solution:

Crystal solution: n = read_line.to_i
puts (1..n).map {
  read_line.split.map(&.to_i64)
}.transpose.sum { |a|
  x = a.sort[n // 2]
  a.sum { |y| (x - y).abs }
}





Kuin solution: func main()
	var n: int :: cui@inputInt()
	var x: []int :: #[n]int
	var y: []int :: #[n]int
	for i(0, n - 1)
		do x[i] :: cui@inputInt()
		do y[i] :: cui@inputInt()
	end for
	do x.sort()
	do y.sort()
	
	var ans: int :: 0
	for i(0, n - 1)
		do ans :+ (x[i] - x[n / 2]).abs()
		do ans :+ (y[i] - y[n / 2]).abs()
	end for
	do cui@print("\{ans}\n")
end func
AtCoder problem 070

C++ solution:


Python solution: class INPUT:
  def __init__(self):
    self._l=open(0).read().split()
    self._length=len(self._l)
    self._index=0
    return

  def stream(self,k=1,f=int,f2=False):
    assert(-1<k)
    if self._length==self._index or self._length-self._index<k:
      raise Exception("There is no input!")
    elif f!=str:
      if k==0:
        ret=list(map(f,self._l[self._index:]))
        self._index=self._length
        return ret
      if k==1 and not f2:
        ret=f(self._l[self._index])
        self._index+=1
        return ret
      if k==1 and f2:
        ret=[f(self._l[self._index])]
        self._index+=1
        return ret
      ret=[]
      for _ in [0]*k:
        ret.append(f(self._l[self._index]))
        self._index+=1
      return ret
    else:
      if k==0:
        ret=list(self._l[self._index:])
        self._index=self._length
        return ret
      if k==1 and not f2:
        ret=self._l[self._index]
        self._index+=1
        return ret
      if k==1 and f2:
        ret=[self._l[self._index]]
        self._index+=1
        return ret
      ret=[]
      for _ in [0]*k:
        ret.append(self._l[self._index])
        self._index+=1
      return ret
pin=INPUT().stream

"""
pin(number[default:1],f[default:int],f2[default:False])
if number==0 -> return left all
listを変数で受け取るとき、必ずlistをTrueにすること。
"""

def main():
  N=pin(1)
  X=[]
  Y=[]
  for _ in[0]*N:
    x,y=pin(2)
    X.append(x)
    Y.append(y)
  X.sort()
  Y.sort()
  ac=-10**9-10
  wa=10**9+10
  #3分探索
  ansx=float("inf")
  searchX=lambda c:sum(abs(c-i)for i in X)
  for _ in[0]*100:
    #print(ac,wa)
    midx1=(2*ac+wa)//3
    midx2=(ac+2*wa)//3
    d1=searchX(midx1)
    d2=searchX(midx2)
    if d1<d2:
      wa=midx2
    else:
      ac=midx1
  ansx=ac
  if searchX(ac)>searchX(wa):
    ansx=wa
  if searchX(wa)>searchX((ac+wa)//2):
    ansx=(wa+ac)//2
  #print(ansx)
  ac=-10**9-10
  wa=10**+10
  searchY=lambda c:sum(abs(c-i)for i in Y)
  for _ in[0]*100:
    #print(ac,wa)
    midy1=(2*ac+wa)//3
    midy2=(ac+2*wa)//3
    d1=searchY(midy1)
    d2=searchY(midy2)
    if d1<d2:
      wa=midy2
    else:
      ac=midy1
  ansy=ac
  if searchY(ac)>searchY(wa):
    ansy=wa
  if searchY(wa)>searchY((ac+wa)//2):
    ansy=(wa+ac)//2
  #print(ansy)
  print(searchX(ansx)+searchY(ansy))
  return

main()

  



Kuin solution: func main()
	var n: int :: cui@inputInt()
	var x: []int :: #[n]int
	var y: []int :: #[n]int
	for i(0, n - 1)
		do x[i] :: cui@inputInt()
		do y[i] :: cui@inputInt()
	end for
	do x.sort()
	do y.sort()
	
	var ans: int :: 0
	for i(0, n - 1)
		do ans :+ (x[i] - x[n / 2]).abs()
		do ans :+ (y[i] - y[n / 2]).abs()
	end for
	do cui@print("\{ans}\n")
end func
AtCoder problem 071

C++ solution:

Crystal solution: class Solve
  getter n : Int32, m : Int32, k : Int32

  def initialize
    @n, @m, @k = read_line.split.map(&.to_i)
    @graph = Array(Array(Int32)).new(n) { [] of Int32 }
    @deg = Array(Int32).new(n, 0)
    m.times do
      a, b = read_line.split.map(&.to_i.pred)
      @graph[a] << b
      @deg[b] += 1
    end
    @ans = [] of Array(Int32)
    @perm = [] of Int32
    @stack = [] of Int32
  end

  def run
    @stack = (0...n).select { |i| @deg[i] == 0 }
    dfs
    puts -1
  end

  def dfs
    if @perm.size == n
      @ans << @perm.dup
      if @ans.size == k
        @ans.each { |t| puts t.join(' ', &.succ) }
        exit
      end
      return
    elsif @stack.size == 0
      puts -1
      exit
    end

    (0...@stack.size).reverse_each do |i|
      v = @stack.delete_at(i)
      @perm << v
      @graph[v].each do |u|
        @deg[u] -= 1
        @stack << u if @deg[u] == 0
      end

      dfs

      @graph[v].each do |u|
        @stack.pop if @deg[u] == 0
        @deg[u] += 1
      end
      @perm.pop
      @stack.insert(i, v)
    end
  end
end

Solve.new.run


Python solution: N,M,K = map(int,input().split())
E = [[] for i in range(N)]
inIdx = [0] * N
for i in range(M):
  a,b = map(int,input().split())
  a -= 1
  b -= 1
  E[a].append(b)
  inIdx[b] += 1

topological_que = []
recursive_stack = []
for i in range(N):
  if inIdx[i] == 0:
    topological_que += [i]
recursive_stack.append([0,len(topological_que)])
topological_que += [0] * (N - len(topological_que))

ans = []
while len(recursive_stack) != 0:
  i = len(recursive_stack) - 1
  st = recursive_stack[-1]
  if i == N:
    ans.append([x for x in topological_que])
    recursive_stack.pop()
    if len(recursive_stack) != 0:
      prei = i-1
      pres = recursive_stack[-1]
      for e in E[topological_que[prei]]: inIdx[e] += 1
      topological_que[prei],topological_que[pres[0]] = topological_que[pres[0]],topological_que[prei]
      recursive_stack[-1][0] += 1
    continue
  if st[1] == i:
    # no valid answer
    break
  if st[0] >= st[1]:
    recursive_stack.pop()
    if len(recursive_stack) != 0:
      prei = i-1
      pres = recursive_stack[-1]
      for e in E[topological_que[prei]]: inIdx[e] += 1
      topological_que[prei],topological_que[pres[0]] = topological_que[pres[0]],topological_que[prei]
      pres[0] += 1
    continue
  if len(ans) == K:
    break

  pres = recursive_stack[-1]
  que_back = pres[1]
  topological_que[i] , topological_que[pres[0]] = topological_que[pres[0]] , topological_que[i]
  p = topological_que[i]
  for e in E[p]:
    inIdx[e] -= 1
    if inIdx[e] == 0:
      topological_que[que_back] = e
      que_back += 1
  recursive_stack.append([ i+1,que_back ])

if len(ans) != K:
  print(-1)
else:
  print("\n".join([" ".join([str(x+1) for x in a]) for a in ans]))
AtCoder problem 071

C++ solution:
// Time Complexity: O((N + M + K) * K)



#include <vector>

#include <iostream>

#include <functional>

using namespace std;

int main() {

	cin.tie(0);

	ios_base::sync_with_stdio(false);

	int N, M, K;

	cin >> N >> M >> K;

	vector<vector<int> > G(N);

	vector<int> deg(N);

	for (int i = 0; i < M; ++i) {

		int a, b;

		cin >> a >> b; --a, --b;

		G[a].push_back(b);

		++deg[b];

	}

	vector<int> st;

	vector<int> perm(N, -1);

	vector<vector<int> > answer_list;

	function<bool(int)> dfs = [&](int depth) {

		if (depth == N) {

			answer_list.push_back(perm);

			return true;

		}

		if (st.empty()) {

			return false;

		}

		for (int i = int(st.size()) - 1; i >= 0; --i) {

			if (answer_list.size() == K) {

				break;

			}

			int x = st[i];

			st.erase(st.begin() + i);

			for (int j : G[x]) {

				--deg[j];

				if (deg[j] == 0) {

					st.push_back(j);

				}

			}

			perm[depth] = x;

			bool sign = dfs(depth + 1);

			if (!sign) {

				return false;

			}

			for (int j : G[x]) {

				if (deg[j] == 0) {

					st.pop_back();

				}

				++deg[j];

			}

			st.insert(st.begin() + i, x);

		}

		return true;

	};

	for (int i = 0; i < N; ++i) {

		if (deg[i] == 0) {

			st.push_back(i);

		}

	}

	dfs(0);

	if (answer_list.size() != K) {

		cout << -1 << endl;

	}

	else {

		for (vector<int> v : answer_list) {

			for (int i = 0; i < N; ++i) {

				if (i != 0) cout << ' ';

				cout << v[i] + 1;

			}

			cout << endl;

		}

	}

	return 0;

}

Crystal solution: class Solve
  getter n : Int32, m : Int32, k : Int32

  def initialize
    @n, @m, @k = read_line.split.map(&.to_i)
    @graph = Array(Array(Int32)).new(n) { [] of Int32 }
    @deg = Array(Int32).new(n, 0)
    m.times do
      a, b = read_line.split.map(&.to_i.pred)
      @graph[a] << b
      @deg[b] += 1
    end
    @ans = [] of Array(Int32)
    @perm = [] of Int32
    @stack = [] of Int32
  end

  def run
    @stack = (0...n).select { |i| @deg[i] == 0 }
    dfs
    puts -1
  end

  def dfs
    if @perm.size == n
      @ans << @perm.dup
      if @ans.size == k
        @ans.each { |t| puts t.join(' ', &.succ) }
        exit
      end
      return
    elsif @stack.size == 0
      puts -1
      exit
    end

    (0...@stack.size).reverse_each do |i|
      v = @stack.delete_at(i)
      @perm << v
      @graph[v].each do |u|
        @deg[u] -= 1
        @stack << u if @deg[u] == 0
      end

      dfs

      @graph[v].each do |u|
        @stack.pop if @deg[u] == 0
        @deg[u] += 1
      end
      @perm.pop
      @stack.insert(i, v)
    end
  end
end

Solve.new.run
AtCoder problem 072

C++ solution:
#include <iostream>

#include <algorithm>

using namespace std;



int H, W;

char c[20][20];

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

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

bool used[20][20];



int dfs(int sx, int sy, int px, int py) {

	if (sx == px && sy == py && used[px][py] == true) return 0;

	used[px][py] = true;



	int ret = -10000;

	for (int i = 0; i < 4; i++) {

		int nx = px + dx[i], ny = py + dy[i];

		if (nx < 1 || ny < 1 || nx > H || ny > W || c[nx][ny] == '#') continue;

		if ((sx != nx || sy != ny) && used[nx][ny] == true) continue;

		int v = dfs(sx, sy, nx, ny);

		ret = max(ret, v + 1);

	}

	used[px][py] = false;

	return ret;

}



int main() {

	// Step #1. Input

	cin >> H >> W;

	for (int i = 1; i <= H; i++) {

		for (int j = 1; j <= W; j++) cin >> c[i][j];

	}



	// Step #2. DFS

	int Answer = -1;

	for (int i = 1; i <= H; i++) {

		for (int j = 1; j <= W; j++) {

			Answer = max(Answer, dfs(i, j, i, j));

		}

	}

	if (Answer <= 2) Answer = -1;

	cout << Answer << endl;

	return 0;

}

Crystal solution: record Point, y : Int32, x : Int32 do
  Direction = [Point.new(0, 1), Point.new(0, -1), Point.new(1, 0), Point.new(-1, 0)]

  def +(other : Point)
    Point.new(y + other.y, x + other.x)
  end
end

class Solve
  getter h : Int32, w : Int32

  def initialize
    @h, @w = read_line.split.map(&.to_i)
    @s = Array(String).new(h) { read_line }
    @ans = 0
    @start = Point.new(0, 0)
    @used = Array(Array(Bool)).new(h) { Array(Bool).new(w, false) }
  end

  def run
    Array.each_product((0...h).to_a, (0...w).to_a) do |(y, x)|
      @start = Point.new(y, x)
      @used.map(&.fill(false))
      @used[y][x] = true
      dfs(@start, 0)
    end
    @ans <= 2 ? -1 : @ans
  end

  def dfs(p1, cnt) : Nil
    (0...4).each do |d|
      p2 = p1 + Point::Direction[d]
      next unless (0...h).includes?(p2.y) && (0...w).includes?(p2.x) && @s[p2.y][p2.x] == '.'
      if @start == p2
        @ans = {@ans, cnt + 1}.max
        return
      end
      if !@used[p2.y][p2.x]
        @used[p2.y][p2.x] = true
        dfs(p2, cnt + 1)
        @used[p2.y][p2.x] = false
      end
    end
  end
end

puts Solve.new.run
AtCoder problem 072

C++ solution:

Crystal solution: record Point, y : Int32, x : Int32 do
  Direction = [Point.new(0, 1), Point.new(0, -1), Point.new(1, 0), Point.new(-1, 0)]

  def +(other : Point)
    Point.new(y + other.y, x + other.x)
  end
end

class Solve
  getter h : Int32, w : Int32

  def initialize
    @h, @w = read_line.split.map(&.to_i)
    @s = Array(String).new(h) { read_line }
    @ans = 0
    @start = Point.new(0, 0)
    @used = Array(Array(Bool)).new(h) { Array(Bool).new(w, false) }
  end

  def run
    Array.each_product((0...h).to_a, (0...w).to_a) do |(y, x)|
      @start = Point.new(y, x)
      @used.map(&.fill(false))
      @used[y][x] = true
      dfs(@start, 0)
    end
    @ans <= 2 ? -1 : @ans
  end

  def dfs(p1, cnt) : Nil
    (0...4).each do |d|
      p2 = p1 + Point::Direction[d]
      next unless (0...h).includes?(p2.y) && (0...w).includes?(p2.x) && @s[p2.y][p2.x] == '.'
      if @start == p2
        @ans = {@ans, cnt + 1}.max
        return
      end
      if !@used[p2.y][p2.x]
        @used[p2.y][p2.x] = true
        dfs(p2, cnt + 1)
        @used[p2.y][p2.x] = false
      end
    end
  end
end

puts Solve.new.run


Python solution: h, w = map(int,input().split())
s = [list(input()) for _ in range(h)]

dist = [[-1] * w for _ in range(h)]
d = ((1, 0), (-1, 0), (0, 1), (0, -1))

def dfs(y: int, x: int, cnt) -> int:
    if dist[y][x] != -1:
        if cnt - dist[y][x] >= 4:
            return cnt - dist[y][x]
        else:
            return -1

    num = -1
    dist[y][x] = cnt
    for dy, dx in d:
        if not (0 <= dy + y <= h - 1 and 0 <= dx + x <= w - 1): continue
        if s[dy + y][dx + x] == "#": continue
        num = max(num, dfs(dy + y, dx + x, cnt + 1))    
    dist[y][x] = -1

    return num

ans = -1
for i in range(h):
    for j in range(w):
        if s[i][j] == "#": continue
        ans = max(ans, dfs(i, j, 0))

print(ans)