我写了下面的代码以及isAdjacentColor方法。如果两个正方形相邻(例如,一个正方形的皇后彼此移开)并且具有相同的颜色或turn(),则isAdjacentColor方法返回true。
我想我已经实施了广度优先搜索。
我想知道如何使用递归调用,因为当前返回的递归调用在探索所有相邻选项之前将返回false。
boolean isContiguous(Square from, Square to, boolean[][] visited) {
if (get(from) != get(to)) {
return false;
}
if (from == to) {
return true;
}
int col = from.col();
int row = from.row();
if (!visited[col][row]) {
visited[col][row] = true;
if (col - 1 >= 0 && row - 1 >= 0) {
Square curr = sq(col - 1, row - 1);
if (isAdjacentColor(from, curr, turn())) {
return isContiguous(curr, to, visited);
}
}
if (row - 1 >= 0) {
Square curr = sq(col, row - 1);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
if (col + 1 < BOARD_SIZE && row - 1 >= 0) {
Square curr = sq(col + 1, row - 1);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
if (col - 1 >= 0) {
Square curr = sq(col - 1, row);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
if (col + 1 < BOARD_SIZE) {
Square curr = sq(col + 1, row);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
if (col - 1 >= 0 && row + 1 < BOARD_SIZE) {
Square curr = sq(col - 1, row + 1);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
if (row + 1 < BOARD_SIZE) {
Square curr = sq(col, row + 1);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
if (col + 1 < BOARD_SIZE && row + 1 < BOARD_SIZE) {
Square curr = sq(col + 1, row + 1);
if (isAdjacentColor(from, curr, get(from))) {
return isContiguous(curr, to, visited);
}
}
}
return false;
}
我写了下面的代码以及isAdjacentColor方法。如果两个正方形相邻(例如,一个正方形的女王移动彼此离开)并且具有相同的...,则isAdjacentColor方法返回true ...
我想我已经通过创建一个ArrayList来存储每个递归调用的答案的方式解决了我的问题。然后最后,如果ArrayList包含true,则返回而不是返回false。