Problem:
Score : 500 points

Problem Statement

Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S.
If S_{i,j} is 1, there is an edge connecting Vertex i and j; otherwise, there is no such edge.

Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division.

Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds.

Constraints

2 \leq N \leq 200

S_{i,j} is 0 or 1.

S_{i,i} is 0.

S_{i,j}=S_{j,i}

The given graph is connected.

N is an integer.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}...S_{1,N}
:
S_{N,1}...S_{N,N}

Output

If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1.
Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition.

Sample Input 1

2
01
10

Sample Output 1

2

We can put Vertex 1 in V_1 and Vertex 2 in V_2.

Sample Input 2

3
011
101
110

Sample Output 2

-1

Sample Input 3

6
010110
101001
010100
101000
100000
010000

Sample Output 3

4

Solution in Java (OpenJDK 11.0.6) (judge verdict: Accepted)

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.rmi.dgc.Lease;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Comparator.*;

public class Main {
	public static void main(String[] args) {
		Main main = new Main();
		main.solve();
		main.out.close();
	}
	// ======================================================================
	final int INF = (int)(1e9);
	Graph G = new Graph();
	int[][] dist;
	public void solve() {
		int N = ni();
		dist = new int[N][N];
		for (int i = 0; i < N; i++) {
			Arrays.fill(dist[i], INF);
		}
		char[] s;
		for (int i = 0; i < N; i++) {
			s = ns().toCharArray();
			for (int j = 0; j < s.length; j++) {
				if(i == j)	continue;
				if(s[j] == '1') {
					G.add(i, j);
					dist[i][j] = 1;
				}
			}
		}
		if(!G.isBipartite()) {
			out.println(-1);	// ２部グラフではない
			return;
		}
		int[][] ans = warshallFloyd(dist);
		int max = 0;
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if(i == j)	continue;
				if(ans[i][j] < INF && ans[i][j] > max)	max = ans[i][j];
			}
		}
		out.println(max+1);
	}
	//
	// 全ての頂点間の最短距離を求める　Ｏ（Ｖ＾３）　Ｖ：頂点の数　→　多いと使えない
	//
	// 引数　　distance 　　は頂点から頂点への距離（頂点は０～　）　☆☆☆　接続していない距離は大きな値を設定しておく事　☆☆☆
	// 返り値　min_distance は全ての頂点から頂点への最短距離の配列（頂点は０～　）
	//
	//  ☆　負の閉路があれば、マイナスの最短距離が返される
	//
	public int[][] warshallFloyd(int[][] distance){
		int node_number = distance.length;
		int[][] min_distance = new int[node_number][node_number];
		for(int i=0;i<node_number;i++) {
			for(int j=0;j<node_number;j++) {
				min_distance[i][j] = distance[i][j];
			}
		}
		for(int via=0;via<node_number;via++) {
			for(int from=0;from<node_number;from++) {
				for(int to=0;to<node_number;to++) {
					min_distance[from][to] = Math.min(min_distance[from][to], min_distance[from][via]+min_distance[via][to]);
				}
			}
		}
		return min_distance;
	}

	// 重みなし　グラフ
	class Graph {
		// 頂点に紐づく頂点のリスト（多重辺は保存されない）
		private Map<Integer, Set<Integer>> data = new HashMap<Integer, Set<Integer>>();
		
		/**
		 * 頂点と頂点の繋がりを追加する
		 */
		void add(int from, int to) {
			Set<Integer> set = data.get(from);
			if (set == null) {
				set = new HashSet<Integer>();
				data.put(from, set);
			}
			set.add(to);
		}
		/**
		 * 始点から終点が繋がっていれば切る
		 */
		void del(int from, int to) {
			Set<Integer> set = data.get(from);
			if (set == null) {
				return;
			}
			if (set.contains(to)) {
				set.remove((Object) to);
			}
		}
		/**
		 * 指定された頂点に紐づく、頂点の Set を返す
		 */
		Set<Integer> getSet(int key) {
			return data.get(key);
		}
		/**
		 * 頂点 key が登録されているか？
		 */
		boolean containsKey(int key) {
			return data.containsKey(key);
		}
		/**
		 * 頂点のセットを返す
		 */
		Set<Integer> keySet() {
			return data.keySet();
		}
		/**
		 * from --> to がつながっていれば　true を返す
		 */
		boolean isConnect(int from, int to) {
			Set<Integer> set = data.get(from);
			if (set == null)
				return false;
			else
				return set.contains(to);
		}
		/**
		 * 指定された頂点から、すべての頂点への距離を返す（幅優先　ＢＦＳ）	→　返り値は配列
		 */
		int[] getDistV(int key) { 					// key : 開始頂点
			int n = data.size();
			int[] dist = new int[n];				// [頂点] = 距離
			Arrays.fill(dist, -1);					// 届かない場合　-1
			Deque<PP> deque = new ArrayDeque<>(); 	// キュー
			deque.offerLast(new PP(key, 0)); 		// スタートをスタックに保存
			dist[key] = 0;
			while (deque.peekFirst() != null) {
				PP wk = deque.pollFirst(); 			// キューから次の頂点を取得
				int no = wk.getKey();
				int dd = wk.getVal();
	//				out.println("キューから取り出し　：　<--  [" + no + "][" + dd + "]");
				Set<Integer> set = getSet(no); 		// つながっている頂点のリストを取得
				if (set != null) {
					for (int next : set) {
						if (dist[next] != -1)
							continue;
						dist[next] = dd + 1; 		// 距離を登録
						deque.offerLast(new PP(next, dd + 1));
	//						out.println("キューに登録　：　-->  [" + next + "][" + (dd + 1) + "]");
					}
				}
			}
			return dist;
		}
		/*
		 * 二部グラフかチェックする
		 */
		boolean isBipartite() {
			int n = data.size();
			int[] color = new int[n];				// [頂点] = 距離
			Arrays.fill(color, -1);					// 未設定　-1
			Deque<PP> deque = new ArrayDeque<>(); 	// キュー
			deque.offerLast(new PP(0, 0)); 			// スタートをスタックに保存
			color[0] = 0;							// 初期の色
			int fnext;
			while (deque.peekFirst() != null) {
				PP wk = deque.pollFirst(); 			// キューから次の頂点を取得
				int no = wk.getKey();
				int dd = wk.getVal();
//				out.println("キューから取り出し　：　<--  [" + no + "][" + dd + "]");
				fnext = (dd == 0 ? 1 : 0);			// 次の色（０／１　交互）
				Set<Integer> set = getSet(no); 		// つながっている頂点のリストを取得
				if (set != null) {
					for (int next : set) {
						if (color[next] != -1) {
							if(color[next] != fnext) {
//								out.println("頂点[" + next + "] の色は[" + color[next] + "]　→　色がちがう");
								return false;
							} else						continue;
						}
						color[next] = fnext; 		// 色を登録
						deque.offerLast(new PP(next, fnext));
//						out.println("キューに登録　：　-->  [" + next + "][" + fnext + "]");
					}
				}
			}
			return true;
		}
		// ================================================================================
		Map<Integer, Integer> mapCnt = new HashMap<>(); // 項番（何番目に訪れたか）
		Map<Integer, Integer> mapLow = new HashMap<>(); // 初期値は項番、つながっている先の項番が小さければコピーする
		// mapCnt > mapLow なら閉路に含まれる頂点
		Set<Integer> mark = new HashSet<>(); 			// 処理したら入れる
		
		// mapCnt, mapLow を設定する
		int bridgeDfs(int now, int pre, int number) {
			mark.add(now);
			mapCnt.put(now, number);
			mapLow.put(now, number);
			int low;
			for (int next : getSet(now)) {
				if (next == pre)
					continue;
				if (mark.contains(next)) {
					if (mapLow.get(now) > mapLow.get(next)) {
						mapLow.put(now, mapLow.get(next));
					}
					continue;
				}
				number++;
				low = bridgeDfs(next, now, number);
				if (mapLow.get(now) > low) {
					mapLow.put(now, low);
				}
			}
			return mapLow.get(now);
		}
		/**
		 * 橋の数を返す  先頭の頂点番号を引数とする
		 */
		int bridgeCnt(int start) {
			mapCnt.clear();
			mapLow.clear();
			mark.clear();
			bridgeDfs(start, start, 0);
			int ans = 0;
			for (int key : mapCnt.keySet()) {
				if (mapCnt.get(key) == mapLow.get(key)) {
					ans++;
				}
			}
			return ans - 1;
		}
		// ================================================================================
		
		/**
		 * ダンプ
		 * @param out
		 */
		void dump() {
			for (int key : data.keySet()) {
				out.print(key + " : ");
				for (int val : data.get(key)) {
					out.print(val + " ");
				}
				out.println("");
			}
		}
	}
	// Set に入れるなら　PPKEY　を使う！
	class PP {
		public int key, val;
		public PP(int key, int val) {
			this.key = key;
			this.val = val;
		}
		public int getKey() {			return key;		}
		public void setKey(int key) {	this.key = key;	}
		public int getVal() {			return val;		}
		public void setVal(int val) {	this.val = val;	}
	}

	// ------------------------------------------
	// ライブラリ
	// ------------------------------------------
	// Print
	private PrintWriter out = new PrintWriter(System.out);
	
	// Scanner
	private FastScanner scan = new FastScanner();
	int ni(){ return scan.nextInt();}
	int[] ni(int n){int[] a = new int[n]; for(int i = 0; i < n; i++){a[i] = ni();} return a;}
	int[][] ni(int y, int x){int[][] a = new int[y][x];
	for(int i = 0; i < y; i++){for(int j = 0; j < x; j++){a[i][j] = ni();}} return a;}
	long nl(){return scan.nextLong();}
	long[] nl(int n){long[] a = new long[n]; for(int i = 0; i < n; i++){a[i] = nl();} return a;}
	long[][] nl(int y, int x){long[][] a = new long[y][x];
	for(int i = 0; i < y; i++){for(int j = 0; j < x; j++){a[i][j] = nl();}} return a;}
	String ns(){return scan.next();}
	String[] ns(int n){String[] a = new String[n]; for(int i = 0; i < n; i++){a[i] = ns();} return a;}
	String[][] ns(int y, int x){String[][] a = new String[y][x];
	for(int i = 0; i < y; i++){for(int j = 0; j < x; j++){a[i][j] = ns();}} return a;}
}
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;
	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		}else{
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}
	private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
	private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
	public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
	public String next() {
		if (!hasNext()) throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while(isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	public long nextLong() {
		if (!hasNext()) throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			}else if(b == -1 || !isPrintableChar(b)){
				return minus ? -n : n;
			}else{
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}
	public int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) nl;
	}
	public double nextDouble() { return Double.parseDouble(next());}
}