How to print all square submatrices of square matrix in C?

强颜欢笑 提交于 2019-12-08 18:46:30

Your code was just printing a single sub-matrix for each size, positioned in the upper-left corner of the matrix. You need to add i and j offsets to get the sub-matrices at all positions:

#include <stdio.h>

int main() {
    int mtrx_size = 8;
    int mat[8][8] = {
        { 1, 2, 3, 4, 5, 6, 7, 8},
        { 9,10,11,12,13,14,15,16},
        {17,18,19,20,21,22,23,24},
        {25,26,27,28,29,30,31,32},
        {33,34,35,36,37,38,39,40},
        {41,42,43,44,45,46,47,48},
        {49,50,51,52,53,54,55,56},
        {57,58,59,60,61,62,63,64}
    };

    int i, j, ioff, joff, off_cnt;
    int sub_mtrx_size;

    for(sub_mtrx_size = mtrx_size; sub_mtrx_size > 1 ; sub_mtrx_size--) {
        off_cnt = mtrx_size - sub_mtrx_size + 1;
        for (ioff = 0; ioff < off_cnt; ioff++) {
            for (joff = 0; joff < off_cnt; joff++) {
                for (i = 0; i < sub_mtrx_size; i++) {
                    for (j = 0; j < sub_mtrx_size; j++) {
                        printf("%3d ", mat[i+ioff][j+joff]);
                    }
                    printf("\n");
                }
                printf("\n");
            }
        }
    }

    return 0;
}

Java implementation for a general nxm matrix:

private static void printSubMatrix(int[][] mat) {
    int rows=mat.length;
    int cols=mat[0].length;

    //prints all submatrix greater than or equal to 2x2
    for (int subRow = rows; subRow >= 2; subRow--) {
        int rowLimit = rows - subRow + 1;
        for (int subCol = cols; subCol >= 2; subCol--) {
            int colLimit = cols - subCol + 1;
            for (int startRow = 0; startRow < rowLimit; startRow++) {
                for (int startCol = 0; startCol < colLimit; startCol++) {

                    for (int i = 0; i < subRow; i++) {
                        for (int j = 0; j < subCol; j++) {
                            System.out.print(mat[i + startRow][j + startCol] + " ");
                        }
                        System.out.print("\n");
                    }
                    System.out.print("\n");

                }
            }
        }
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!