// Arup Guha
// 4/27/2019
// Solution for AP CS FR Question #4: Successors

public class Successors {

	// Returns the lexicographically first position in intArr that contains num.
	// This means that if num is in (r1, c1) and (r2, c2), if r1 < r2, then
	// (r1, c1) is returned. Also, if r1 == r2 and c1 < c2, then (r1, c1) is
	// returned. Otherwise (r2, c2) would take precedence.
	public static Position findPosition(int num, int[][] intArr) {
	
		// Go in row-col order...
		for (int i=0; i<intArr.length; i++)
			for (int j=0; j<intArr[i].length; j++)
				
				// We found num, return the appropriate position object.
				if (intArr[i][j] == num)
					return new Position(i, j);
					
		// If we make it here, we never found num...
		return null;
	}
	
	public static Position[][] getSuccessorArray(int[][] intArr) {
		
		// Not necessary, but I am making this work even when the different 1D arrays
		// are of different lengths.
		Position[][] res = new Position[intArr.length][];
		for (int i=0; i<res.length; i++)
			res[i] = new Position[intArr[i].length];
		
		// Just call findPosition for each slot.
		for (int i=0; i<res.length; i++)
			for (int j=0; j<res[i].length; j++)
				res[i][j] = findPosition(intArr[i][j]+1, intArr);
			
		return res;
	}
	
	// So we can visualize a position array easily.
	public static void print(Position[][] posArr) {
		
		for (int i=0; i<posArr.length; i++) {
			
			for (int j=0; j<posArr[i].length; j++) {
				if (posArr[i][j] != null)
					System.out.print(posArr[i][j]+" ");
				else
					System.out.print("null ");
			}
			System.out.println();
		}
	}
	
	public static void main(String[] args) {
		
		// This is their example...
		int[][] grid = {{15,5,9,10},{12,16,11,6},{14,8,13,7}};
		Position[][] res = getSuccessorArray(grid);
		print(res);
	}
}