gpt4 book ai didi

java - Java 中的队列 - 我的实现有什么问题,我可以使用什么?

转载 作者:行者123 更新时间:2023-11-30 04:56:44 26 4
gpt4 key购买 nike

我正在尝试进行广度优先搜索来解决方 block 移动难题(将方 block 移动到空白空间直到解决的难题)。我的广度优先算法使用队列。不幸的是,它似乎只适用于 UP 和 DOWN 情况,而不适用于 LEFT 或 RIGHT 情况:

                if (up)
{
int[][] current = copy(v.state);
current[x][y] = current[x - 1][y];
current[x - 1][y] = 0;

State w = new State(current);
w.distance = v.distance + 1;
w.path = v;
System.out.println(q.insert(w));
}

if (down)
{
int[][] current = copy(v.state);
current[x][y] = current[x + 1][y];
current[x + 1][y] = 0;

State w = new State(current);
w.distance = v.distance + 1;
w.path = v;
System.out.println(q.insert(w));
}

if (left)
{
int[][] current = copy(v.state);
current[x][y] = current[x][y - 1];
current[x][y - 1] = 0;

State w = new State(current);
w.distance = v.distance + 1;
w.path = v;
System.out.println(q.insert(w));
}

if (right)
{
int[][] current = copy(v.state);
current[x][y] = current[x][y + 1];
current[x][y + 1] = 0;

State w = new State(current);
w.distance = v.distance + 1;
w.path = v;
System.out.println(q.insert(w));
}

我认为这是我的队列的问题,其实现如下。我的队列有问题还是其他问题? Java API 是否有我可以使用的队列类?

public class ArrayQueue {
State[] items;
int maxSize;
int front;
int rear;
int numItems;

public ArrayQueue(int max)
{
items = new State[max];
maxSize = max;
front = 0;
rear = -1;
numItems = 0;
}

public boolean insert(State item)
{
if (isFull()) return false;
rear = (rear + 1) % items.length;
items[rear] = item;
return true;
}

public State remove()
{
if (isEmpty()) return null;
State removed = items[front];
front = (front + 1) % items.length;
return removed;
}

public boolean isFull()
{
if ((front + 1) % maxSize == rear)
return true;
else
return false;
}

public boolean isEmpty()
{
if ((rear + 1) % maxSize == front)
return true;
else
return false;
}
}

复制方法如下:

public static int[][] copy(int[][] input)       //This method is necessary because we are trying to clone a multi-dimensional array.
{ //Just using clone() will copy the outer arrays but they will be arrays of references to the original inner arrays.
int[][] output = new int[input.length][];
for (int i = 0; i < input.length; i++)
output[i] = input[i].clone();
return output;
}

最佳答案

JDK 提供了Queue 接口(interface)和许多实现,可以在Queue documentation 的“所有已知实现类”部分中找到。 .

为了您的目的,LinkedList应该足够好了。

关于java - Java 中的队列 - 我的实现有什么问题,我可以使用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8304609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com