Finding sub matrix of a given matrix

Ashwani Kumar picture Ashwani Kumar · Mar 27, 2012 · Viewed 19k times · Source

i am trying to write an algorithm for finding a sub matrix in a given sub matrix. To solve this problem i had written the following code:

public class SubMatTry {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int a[][] = { { 2, 3, 5, 7 }, { 5, 8, 3, 5 }, { 7, 6, 9, 2 },
            { 3, 8, 5, 9 } };
    int b[][] = { { 9, 2 }, { 5, 9 } };
    int k = 0;
    int l = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            System.out.println("Element of a= " + a[i][j]);
            if (b[k][l] == a[i][j]) {
                System.out.println(b[k][l] + " = " + a[i][j]);
                if (b[k][l + 1] == a[i][j + 1]) {
                    System.out.println(b[k][l + 1] + " = " + a[i][j + 1]);
                    if (b[k + 1][l] == a[i + 1][j]) {
                        System.out.println(b[k + 1][l] + " = "
                                + a[i + 1][j]);
                        if (b[k + 1][l + 1] == a[i + 1][j + 1]) {
                            System.out.println(b[k + 1][l + 1] + " = "
                                    + a[i + 1][j + 1]);
                            System.out.println("Array found at" + i + " ,"
                                    + j);
                            System.exit(0);
                        }
                    }
                }
            }
        }

    }

}}

This code is working fine but i am not sure it is the exact solution of the problem or its just a work around. Please provide your expert comments. Thanks in advance.

Answer

aioobe picture aioobe · Mar 27, 2012

The algorithm is hard-coded for a 4×4 matrix and a 2×2 submatrix. Otherwise it looks fine as a brute-force algorithm.

I would have expressed it as follows:

outerRow:
for (int or = 0; or <= a.length - b.length; or++) {
    outerCol:
    for (int oc = 0; oc <= a[or].length - b[0].length; oc++) {
        for (int ir = 0; ir < b.length; ir++)
            for (int ic = 0; ic < b[ir].length; ic++)
                if (a[or + ir][oc + ic] != b[ir][ic])
                    continue outerCol;
        System.out.println("Submatrix found at row " + or + ", col " + oc);
        break outerRow;
    }
}

If you want something more efficient, I suggest you flatten them out, like this:

{ 2,3,5,7, 5,8,3,5, 7,6,9,2, 3,8,5,9 }

and search this sequence for the following pattern:

{ 9,2, _, _, 5, 9}

using standard find-substring techniques such as Aho-Corasick or Knuth-Morris-Pratt algorithm. (Note that you would have to skip some indexes to avoid false positives where there's a new row in the middle of the sequence.)