// Arup Guha
// 8/15/2019
// Solution for 2018 AP FR Question #4: ArrayTester

import java.util.*;

public class ArrayTester {

	public static int[] getColumn(int[][] arr2D, int c) {
		
		// Allocate space.
		int[] res = new int[arr2D.length];
		
		// Copy stuff over; first index changes, second does not.
		for (int i=0; i<res.length; i++)
			res[i] = arr2D[i][c];
		
		// Return it.
		return res;
	}
	
	public static boolean hasAllValues(int[] arr1, int[] arr2) {
		
		// This just makes our task easier.
		HashSet<Integer> hs = new HashSet<Integer>();
		for (int x: arr2) hs.add(x);
		
		// Check each value in arr1 to see if it's in our hashset.
		for (int x: arr1) 
			if (!hs.contains(x))
				return false;
			
		// If we get here, we found everything in arr2.
		return true;
	}
	
	public static boolean containsDuplicates(int[] arr) {
		
		// Makes our life easier again.
		HashSet<Integer> hs = new HashSet<Integer>();
		
		// Go through each value.
		for (int x: arr) {
			
			// We added this one before...so we have a duplicate.
			if (hs.contains(x)) return true;
			hs.add(x);
		}
		
		// If we get here, we never had a duplicate.
		return false;
	}
	
	public static boolean isLatin(int[][] square) {
		
		// Rule #1...
		if (containsDuplicates(square[0])) return false;
		
		// Rule #2: Check all other rows against the first row
		for (int i=1; i<square.length; i++)
			if (!hasAllValues(square[0], square[i]))
				return false;
			
		// Rule #3: Check all columns; use the method to obtain each column as an array...
		for (int i=0; i<square.length; i++) {
			int[] col = getColumn(square, i);
			if (!hasAllValues(square[0], col))
				return false;
		}
		
		// If we get here, we're good!
		return true;
	}
	
	public static void main(String[] args) {
		
		int[][] sq1 = {{1,2,3},{2,3,1},{3,1,2}};
		int[][] sq2 = {{10,30,20,0},{0,20,30,10},{30,0,10,20},{20,10,0,30}};
		int[][] sq3 = {{1,2,1},{2,1,1},{1,1,2}};
		int[][] sq4 = {{1,2,3},{3,1,2},{7,8,9}};
		int[][] sq5 = {{1,2},{1,2}};
		System.out.println(isLatin(sq1));
		System.out.println(isLatin(sq2));
		System.out.println(isLatin(sq3));
		System.out.println(isLatin(sq4));
		System.out.println(isLatin(sq5));
		
	}
}