寻找给定矩阵的子矩阵

时间:2012-03-27 07:33:22

标签: java multidimensional-array submatrix

我正在尝试编写一种算法,用于在给定的子矩阵中查找子矩阵。为了解决这个问题,我编写了以下代码:

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);
                        }
                    }
                }
            }
        }

    }

}}

此代码工作正常,但我不确定它是问题的确切解决方案还是只是一个解决方法。请提供您的专家意见。提前谢谢。

4 个答案:

答案 0 :(得分:8)

该算法针对4×4矩阵和2×2子矩阵进行了硬编码。否则它看起来很好用作蛮力算法。

我会表达如下:

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;
    }
}

如果你想要更高效的东西,我建议你把它们弄平,就像这样:

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

并在此序列中搜索以下模式:

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

使用标准的查找子字符串技术,例如Aho-CorasickKnuth-Morris-Pratt algorithm。 (请注意,您必须跳过一些索引以避免在序列中间有新行的误报。)

答案 1 :(得分:1)

首先,i和j不应该迭代到3(如果你在[3] [3]你知道它不能是一个子矩阵的开始,因为基本上你是在最后矩阵)。

其次,不要使用固定数字,例如4 - 使用a.length代替(这会给你数组的长度a - 列的数量,而[0] .length会给你一个第一列的长度 - 有效,行数)。

第三,我将四倍if(sic)更改为k和l上的双for迭代,如下所示:

for (int i = 0; i < a.length - b.length + 1; i++) {
        for (int j = 0; j < a[0].length - b[0].length + 1; j++) {
            boolean submatrix = true; // at start we assume we have a submatrix
            for (int k = 0; k < b.length; ++k) {
                for (int l = 0; l < b[0].length; ++l) {
                    if (a[i + k][j + l] == b[k][l]) {
                        System.out.println("a[" + (i + k) + "][" + (j + l) + "] = b[" + k + "][" + l + "]");
                    } else {
                        submatrix = false; // we found inequality, so it's not a submatrix
                    }
                }
            }
            if (submatrix) {
                System.out.println("Found subatrix at " + i + "," + j + ".");
            }
        }
    }

(不确定它是否完全正常,没有通过编译器;))

除此之外,如果你使用java,你应该尝试习惯对象,类和方法(Matrix类与boolean isSubmatrix(Matrix b)方法) - 但对于应该这样做的初学者。

希望我的回答有所帮助。

答案 2 :(得分:0)

以下是我根据@aioobe

描述的策略编写的解决方案
public static boolean matrixContainsPattern(int[][] data, int[][] pattern) {
    int[] flatData = flattenMatrix(data);
    int[] flatPattern = flattenMatrix(pattern);

    //If the # of rows of data is less than the rows of pattern, we have a problem since we can match at most only a partial amount of the pattern into data
    if (flatData.length < flatPattern.length) {
        throw new IllegalArgumentException();
    }

    int dataRowLen = data[0].length;
    int patternRowLen = pattern[0].length;
    for (int i = 0; i < flatData.length - flatPattern.length + 1; i++) {
        //We found a potential match for the pattern
        if (flatData[i] == flatPattern[0]) {
            //k can keep track of indexes inside flatData
            int k = i;
            //l can keep track of indexes inside flatPattern
            int l = 0;
            //dataRowOffset will help us keep track of WHERE we found a match in flatPatterns' imaginary rows
            int dataRowOffset = (i % dataRowLen);
            //count to keep track of when we've reached the end of an imaginary row in data
            int count = 1;
            boolean patternFound = true;
            while (k < flatData.length && l < flatPattern.length) {
                if (flatData[k] != flatPattern[l]) {
                    patternFound = false;
                    break;
                }
                //if we reached the end of an imaginary row, we need to skip our pointer k to the next rows offset location
                //we also need to reset count to the offset, so we can again find the end of this new imaginary row
                if (count == patternRowLen) {
                    //To get to the position in the next row of where we first found our match, we add to k: the length of whats remaining in our current row,
                    //plus the offset from where we first found in the match in the current row
                    if (dataRowLen == patternRowLen) {
                        k++;
                    } else {
                        k += (dataRowLen - patternRowLen) + dataRowOffset;
                    }
                    count = 1;
                } else {
                    k++;
                    count++;
                }
                l++;
            }
            if (patternFound) {
                return true;
            }
        }
    }
    return false;
}

将矩阵展平为数组的方法如下:

private static int[] flattenMatrix(int[][] matrix) {
        if (matrix == null || matrix[0] == null || matrix[0].length < 1) {
            throw new IllegalArgumentException();
        }
        int[] flattened = new int[matrix.length * matrix[0].length];

        int k = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                flattened[k] = matrix[i][j];
                k++;
            }
        }
        return flattened;
    }

答案 3 :(得分:0)

将两个矩阵都作为输入,在这里,n,m代表较大的矩阵,r,c代表子矩阵:-

int ans=0,f=0;
    for(int i=0;i<n-r+1;i++)
    {
        for(int j=0;j<m-c+1;j++)
        {
            f=0;
            for(int p=0;p<r;p++)
            {
                for(int q=0;q<c;q++)
                {
                    if(a[i+p][j+q]!=b[p][q])
                    {
                        f=1;
                        break;
                    }
                }
            }
            if(f==0)
            {
                ans=1;
                break;
            }
        }
        if(ans==1)
        break;
    }
     cout<<(ans?"YES":"NO")<<'\n';