Competitive Programming: POJ 2185 – Milking Grid

Description

Every morning when they are milked, the Farmer John’s cows form a rectangular grid that is R (1 <= R <= 10,000) rows by C (1 <= C <= 75) columns. As we all know, Farmer John is quite the expert on cow behavior, and is currently writing a book about feeding behavior in cows. He notices that if each cow is labeled with an uppercase letter indicating its breed, the two-dimensional pattern formed by his cows during milking sometimes seems to be made from smaller repeating rectangular patterns.

Help FJ find the rectangular unit of smallest area that can be repetitively tiled to make up the entire milking grid. Note that the dimensions of the small rectangular unit do not necessarily need to divide evenly the dimensions of the entire milking grid, as indicated in the sample input below.

Input

  • Line 1: Two space-separated integers: R and C
  • Lines 2..R+1: The grid that the cows form, with an uppercase letter denoting each cow’s breed. Each of the R input lines has C characters with no space or other intervening character.

Output

  • Line 1: The area of the smallest unit from which the grid is formed

Sample Input

2 5
ABABA
ABABA

Sample Output

2

Hint

The entire milking grid can be constructed from repetitions of the pattern ‘AB’.

Link to problem

Solution below . . .

Solution

This is very similar to the POJ 1961 problem of finding periodic strings, but in this case we’re asked to do it in two dimensions.

See that link for more detail, but by treating each row as a “letter,” we can use the same KMP algorithm to find the length of repetitive patterns. We do the same for columns, then multiply the two results to get the area.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
  static int[] computeLPSArray(char[][] str, int M) {

    int len = 0;
    int i;

    int[] lps = new int[M];

    lps[0] = 0; // lps[0] is always 0
    i = 1;

    // calculate the rest of the lps array
    while (i < M) {
      if (Arrays.equals(str[i], str[len])) {
        len++;
        lps[i] = len;

        i++;
      } else {
        if (len != 0) {
          len = lps[len - 1];
        } else {
          lps[i] = 0;
          i++;
        }
      }
    }
    return lps;
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int R = sc.nextInt();
    int C = sc.nextInt();

    char s[][] = new char[R][C];
    char c[][] = new char[C][R];

    for (int i = 0; i < R; i++) {
      s[i] = sc.next().toCharArray();
    }

    sc.close();

    // transpose the matrix
    for (int i = 0; i < R; i++) {
      for (int j = 0; j < C; j++)
        c[j][i] = s[i][j];
    }

    int next1[] = computeLPSArray(s, R);
    int next2[] = computeLPSArray(c, C);

    System.out.println((R - next1[R - 1]) * (C - next2[C - 1]));
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *