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.
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:
If you want something more efficient, I suggest you flatten them out, like this:
and search this sequence for the following pattern:
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.)
What follows is a solution I wrote based off the described strategy by @aioobe
And the method to flatten a matrix into an array is as follows:
First of all, i and j should not iterate up to 3 (if you are on a[3][3] you know it can't be a start of a submatrix, cause basically you're at the end of the matrix).
Secondly, don't use fixed numbers, like 4 - use a.length instead (this gives you length of array a - number of columns, while a[0].length would give you a length of first column - effectively, number of rows).
Thirdly, I'd change the quadruple
if
(sic) into a doublefor
iterating on k and l, like that:(Not sure if it exactly works, didn't put it through compiler ;) )
Other than that if you use java, you should try to get used to objects, classes and methods (
Matrix
class withboolean isSubmatrix(Matrix b)
method) - but for starters that should do.Hope my answer helps.