我想从中间元素(第 2 行,第 2 列)的 (1,1) 起始位置遍历一个大 7*7 矩阵内的 3*3 子矩阵。位置 (1,1) 对应的子矩阵将是
[(0,1),(0,2),(0,3)] [(1,1),(1,2),(1,3)] [(2,1),(2,2),(2,3)]
像这样遍历将继续..下一个子矩阵起始位置将是 (1,2)
[(0,2),(0,3),(0,4)] [(1,2),(1,3),(1,4)] [(2,2),(2,3),(2,4)]
我的代码
static int i;
static int j;
static int g;
static int h;
static void submatrix(int p,int q,int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(p+","+q);
shiftmatrix(p,q,mat);
}
static void shiftmatrix(int p,int q,int[][] mat) {
int m,n;
int[][] d = new int[3][3];
for( m=0;m<3;m++) {
for( n=0;n<3;n++) {
p=m+(p-1);
q=n+q;
d[m][n]=mat[p][q];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for ( m = 0; m < 3; m++){
for ( n = 0; n < 3; n++){
System.out.print(d[m][n]+"\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = new int[7][7];
int[][] mat = new int[7][7];
for ( i = 0; i < 7; i++)
{
for ( j = 0; j < 7; j++){
Random rand = new Random();
a[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (i = 0; i < 7; i++){
for (j = 0; j < 7; j++){
mat[g][h]=a[i][j];
System.out.print(mat[g][h]+"\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (i=1;i<6;i++) {
for (j=1;j<5;j++) {
int p=i;
int q=j;
submatrix(p,q,mat);
}
}
}
}
运行此代码时出现错误
ArrayIndexOutOfBoundsException: -1
请帮忙
潇湘沐
相关分类