cuốn sách gpt4 ai đã làm

Một cách khác để viết hàm đệ quy này?

In lại Tác giả: Taklimakan Thời gian cập nhật: 2023-11-02 19:16:08 hai mươi bốn 4
mua khóa gpt4 Nike

我有一个颜色网格(在 2D ArrayList 中)。我需要能够计算在特定色 block 中共享相同颜色的单元格的数量(它们必须在 4 个边上相邻)。我可以很容易地递归地做到这一点,但问题是一些图像会溢出堆栈,因为色 block 可能太大了。

这是递归函数:

private int getBlockCount(PietCodel codel) {

if (codel.getValue() != PietCodel.DEFAULT && codel.getValue() != PietCodel.CHECKED) {
return codel.getValue();
}

ArrayList list = blockCountHelper(codel);
list.add(codel);

// Use the array of codels in the block, and
// use the size to for each value in the array.
int result = list.size();
for (PietCodel item : list) item.setValue(result);

System.out.println("Block count: " + result);

return result;
}

private ArrayList blockCountHelper(PietCodel codel) {
ArrayList result = new ArrayList<>();
codel.setValue(PietCodel.CHECKED);
int col = codel.getCol();
int row = codel.getRow();

// Right
PietCodel ajac = get(col + 1, row);
if (ajac != null && codel.equals(ajac.getColor()) && ajac.getValue() == PietCodel.DEFAULT) {
ArrayList nextCodels = blockCountHelper(ajac);
result.add(ajac);
result.addAll(nextCodels);
}

// Down
ajac = get(col, row + 1);
if (ajac != null && codel.equals(ajac.getColor()) && ajac.getValue() == PietCodel.DEFAULT) {
ArrayList nextCodels = blockCountHelper(ajac);
result.add(ajac);
result.addAll(nextCodels);
}

// Left
ajac = get(col - 1, row);
if (ajac != null && codel.equals(ajac.getColor()) && ajac.getValue() == PietCodel.DEFAULT) {
ArrayList nextCodels = blockCountHelper(ajac);
result.add(ajac);
result.addAll(nextCodels);
}

// Up
ajac = get(col, row - 1);
if (ajac != null && codel.equals(ajac.getColor()) && ajac.getValue() == PietCodel.DEFAULT) {
ArrayList nextCodels = blockCountHelper(ajac);
result.add(ajac);
result.addAll(nextCodels);
}

return result;
}

对使用循环或其他东西的替代方案有什么想法吗?

câu trả lời hay nhất

想法是在您的应用程序代码中明确显示“堆栈/队列”。请注意,这并不比递归方法使用更少的内存,它只是通过利用堆可以使用更多内存。下面的代码是一个例子。请注意,您可以调用 queue.addFirst hoặc queue.addLast,这将不会改变最终结果,但会给你不同的棋盘遍历,这是你可能关心或不关心的事情。

private ArrayList blockCountHelper(PietCodel codel) {
ArrayList accumulator = new ArrayList<>();
LinkedList queue = new LinkedList<>();
queue.add(codel);

while (!queue.isEmpty()) {
PietCodel ajac = queue.remove();
if (ajac != null && codel.equals(ajac.getColor()) .... ) {
accumulator.add(ajac);
}
if ( get(col + 1, row) != null ) {queue.addFirst(get(col + 1, row));}
if ( get(col , row + 1) != null ) {queue.addFirst(get(col, row + 1));}
if ( get(col - 1, row) != null ) {queue.addFirst(get(col - 1, row));}
if ( get(col , row - 1) != null ) {queue.addFirst(get(col, row- 1));}
}
return accumulator;
}

关于java - 编写此递归函数的另一种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125048/

hai mươi bốn 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress