מסתתר שם באג קטן...
הבאג נובע מזה שהספירה מתחילה מ - 0 אבל בתחלס צריכה לייצג גודל, כלומר ספירה שמתחילה ב 1
package test;
public class Driver
{
public static int method(int[][] arr)
{
int count = 0;
// check if the last element of the main diagonal meets the minimal criteria
if (arr[arr.length -1][arr.length - 1] != 1)
{
return 0;
}
// take steps back, counting the number of steps taken back that creates a sub-matrix
// that meets the criteria
for (int i = arr.length - 2; i >= 0; --i)
{
// if the first element of the sub-matrix doesn't equal one -> exit
if (arr != 1)
{
// if it is the second element from the end of the main diagonal
if (i == (arr.length - 2))
{
return count;
}
else
{
return count + 1;
}
}
else
{
boolean bugFound = false;
for (int k = i; k < arr.length; k++)
{
for (int l = i ; l < arr.length; l++)
{
// try to fail the number the 2 criteria tests
if (k == l && arr[k][l] != 1)
{
// main diagonal criteria failed
bugFound = true;
}
else if (k != l && arr[k][l] != 0)
{
// surrounding null elements criteria failed
bugFound = true;
}
// if the number had failed the test - the current sub-matrix
// doesn't meet the criteria, thus the later matrices will not
// meet them as well - return what we've counted thus far.
if (bugFound)
{
return count + (i == arr.length - 2 ? 0 : 1);
}
}
}
// no test failed - this sub-matrix is OK, count it.
count++;
}
}
// we've successfully iterated over the whole matrix and it meets the criteria.
return count + 1;
}
public static void main(String[] args)
{
int[][] badArray = {{1,0,2,0,0},{0,1,0,0,0},{2,3,4,5,6},{1,2,3,4,5},{0,1,0,2,5}};
int[][] goodArray = {{0,0,1,2,3},{0,0,2,0,3},{1,5,3,0,0},{0,1,2,1,0},{0,1,0,0,1}};
int[][] bestCase = {{1,0,0,0,0},{0,1,0,0,0},{0,0,1,0,0},{0,0,0,1,0},{0,0,0,0,1}};
int[][] bestCase2 = {{0,0,0,0,0},{0,1,0,0,0},{0,0,1,0,0},{0,0,0,1,0},{0,0,0,0,1}};
int[][] bugcheck = {{0,0,0,0,0},{0,1,0,0,0},{0,0,1,0,0},{0,0,0,1,0},{0,0,0,1,1}};
int[][] bugcheck2 = {{1,1,0,0,0},{0,1,0,0,0},{0,0,1,0,0},{0,0,0,1,0},{0,0,1,0,1}};
System.out.println("bad array: " + method(badArray) + " expected : 0");
System.out.println("good array: " + method(goodArray) + " expected : 2");
System.out.println("best array: " + method(bestCase) + " expected : 5");
System.out.println("best2 array: " + method(bestCase2) + " expected : 4");
System.out.println("bugcheck array: " + method(bugcheck) + " expected : 0");
System.out.println("bugcheck2 array: " + method(bugcheck2) + " expected : 2");
}
}