我有问题在大矩阵M中找到一些最小的子矩阵m并且m = M / 2;
我需要在相同的循环中找到子矩阵的数量以找到最小的子矩阵
这就是我所做的。
public static void FindSmalSubMatrix(int mat3[][],int rows,int colums)
{
int subm,i,j,temp=0,location1=0,location2=0, min=0;
ArrayList submin = new ArrayList();
if(rows>=colums)
subm=colums/2;
else
subm= rows/2;
min= Firstmin(mat3,subm);
for (i=0;i<rows-subm+1;i++)
for(j=0;j<colums-subm+1;j++)
{
for(int k=i; k <i+subm;k++)
for (int l =j;l<j+subm;l++)
{
temp=temp+ mat3[k][l];
}
if (temp <= min)
{
min=temp;
submin.add(min);
location1=i;
location2=j;
}
temp=0;
}
System.out.println(min+" location is :"+location1+" "+location2);
for( Object value:submin)
System.out.print(value);
}
这是一个例子
6 6 4 4 3
2 2 3 3 8
5 0 2 2 5
4 9 2 1 4
1 6 8 1 3
7位置是:2 2
161514977
但我需要打印出来
min = 7
地点:1 1
2 3
0 2
min = 7
地点:2 2
2 2
1 2
如果有人可以帮助我,我会非常感激。
答案 0 :(得分:0)
你的代码不是那么糟糕。 您是否尝试调试它并检查保存到submin的内容? 因为它看起来像16,15,14,9,7,7(最后2个数字是好的,不是吗?) 什么是FirstMin?
public static void FindSmalSubMatrix(int mat3[][],int rows,int colums)
{
int subm,i,j,temp=0,location1=0,location2=0, min=0;
ArrayList<Point> locations = new ArrayList<Point>();
if(rows>=colums)
subm=colums/2;
else
subm= rows/2;
min= Integer.MAX_VALUE;
for (i=0;i<rows-subm+1;i++)
for(j=0;j<colums-subm+1;j++)
{
temp = 0;
for(int k=i; k <i+subm;k++)
for (int l =j;l<j+subm;l++)
{
temp=temp+ mat3[k][l];
}
if (temp < min)
{
locations.clear(); //you dont need data about larger min, right?
min=temp;
Point point = new Point(i,j);
locations.add(point);
} else (temp == min) {
Point point = new Point(i,j);
locations.add(point);
}
}
// And to print use something like these, but its better to create new class
// which contain location and small matrixes or just use old bigger to print parts
// for example just print location (min are equal to all result) and using
// location print parts from mat3
}
我认为我在这个例子中犯了一些错误,但你会发现它;) 我使用Point类只是为了保存最小矩阵的位置,你可以使用另一个类
修改强> 我不得不修理它,因为我的代码很难看(但仍然无论如何......)