How to finding smaller 2D array inside a bigger 2D array?

Bài viết này sẽ hướng dẫn cách tìm một mảng array 2D, xem nó có tồn tại hay không tổn tại trong một mảng array 2D lớn khác, nếu tồn tại thì in ra vị trí của điểm đầu tiên được tìm thấy trong mảng array 2D lớn.

Source Code - Mã nguồn:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package z_test;

/**
 *
 * @author Bui Ngoc Son
 * @website vnlives.net
 * @version 1.0
 * @create 26/11/2014
 */
public class FindSmaller2dArrInBig2dArr {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        FindSmaller2dArrInBig2dArr main = new FindSmaller2dArrInBig2dArr();
        main.runTest();
    }

    public void runTest() {

        int[][] A1 = new int[5][5];
        A1[0][0] = 1;
        A1[1][0] = 1;
        A1[2][0] = 1;
        A1[3][0] = 1;
        A1[4][0] = 1;
        A1[0][1] = 1;
        A1[1][1] = 1;
        A1[2][1] = 1;
        A1[3][1] = 1;
        A1[4][1] = 1;
        A1[0][2] = 0;
        A1[1][2] = 1;
        A1[2][2] = 1;
        A1[3][2] = 0;
        A1[4][2] = 0;
        A1[0][3] = 0;
        A1[1][3] = 1;
        A1[2][3] = 1;
        A1[3][3] = 0;
        A1[4][3] = 0;
        A1[0][4] = 1;
        A1[1][4] = 1;
        A1[2][4] = 1;
        A1[3][4] = 1;
        A1[4][4] = 1;

        int[][] A2 = new int[2][2];
        A2[0][0] = 0;
        A2[1][0] = 0;
        A2[0][1] = 0;
        A2[1][1] = 0;

        matrix2DMatch(A1, A2);
    }

    private void matrix2DMatch(int[][] matrix, int[][] subMatrix) {

        loopX:
        for (int x = 0; x < matrix.length - subMatrix.length + 1; ++x) {
            loopY:
            for (int y = 0; y < matrix[x].length - subMatrix[0].length + 1; ++y) {
                for (int xx = 0; xx < subMatrix.length; ++xx) {
                    for (int yy = 0; yy < subMatrix[0].length; ++yy) {
                        if (matrix[x + xx][y + yy] != subMatrix[xx][yy]) {
                            continue loopY;
                        }
                    }
                }

                // Found the submatrix!
                System.out.println("-- Found sub matrix at: " + x + " x " + y);
                break loopX;
            }
        }

    }
}


Result - Kết quả:





No comments:

Post a Comment