我正在进行谷歌挑战,我必须解决一个难题。对于这个难题,我必须测试在任何四边触摸它的任何数字是否等于一。如果是这样,我必须改变相反的方向。如果一个则为零。如果为零。当我尝试运行以下代码时,我试图运行它的代码实验室说下面的" Code Timed Out"。我查了一下,d看起来循环应该是无限的。无论它最终应该返回-1还是步数。任何人都可以解释这一点。
import java.util.Arrays;
public class FooReal {
public static boolean[] elementsOn = {false, false};
public static void main(String args[]) {
int[][] grid = {{1, 1}, {0, 0,}};
System.out.println(answer(grid));
}
public static int answer(int[][] grid) {
int steps = 0;
while (containsOn(grid)) {
for (int index = 0; index < grid.length; index++) {
for (int subIndex = 0; subIndex < grid[index].length; subIndex++) {
if (grid[index][subIndex] == 1) {
elementsOn = isElementOn(grid, new int[] {index, subIndex});
if (elementsOn[0] || elementsOn[1]) {
steps++;
for (int counter = 0; counter < grid.length; counter++) {
if (grid[counter][subIndex] == 1) {
grid[counter][subIndex] = 0;
} else {
grid[counter][subIndex] = 1;
}
}
for (int counterTwo = 0; counterTwo < grid[index].length; counterTwo++) {
if (grid[index][counterTwo] == 1) {
grid[index][counterTwo] = 0;
} else {
grid[index][counterTwo] = 1;
}
}
if (grid[index][subIndex] == 1) {
grid[index][subIndex] = 0;
} else {
grid[index][subIndex] = 1;
}
}
}
}
if (steps > 15) {
steps = -1;
return steps;
}
}
}
return steps;
}
public static boolean[] isElementOn(int[][] grid, int[] elements) {
boolean[] elementsOn = {false, false};
//Check if any are on in x row.
try {
if (grid[elements[0] + 1][elements[1]] == 1) {
elementsOn[0] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
try {
if (grid[elements[0] - 1][elements[1]] == 1) {
elementsOn[0] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
//Check if any are on in y row.
try {
if (grid[elements[0]][elements[1] + 1] == 1) {
elementsOn[1] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
try {
if (grid[elements[0]][elements[1] - 1] == 1) {
elementsOn[1] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
return elementsOn;
}
public static boolean containsOn(int[][] grid) {
for (int index = 0; index < grid.length; index++) {
for (int subIndex = 0; subIndex < grid[index].length; subIndex++) {
if (grid[index][subIndex] == 1) {
return true;
}
}
} return false;
}
}