[英]Java Iterating Through 2D-Array
我在Java中有一個2D數組,如下所示:
int 2d_arr[5][5];
以如下所示的板子為例:
1 1 1 1 1
0 1 1 1 1
1 1 2 1 0
0 1 1 1 1
0 0 1 1 1
從第三行的2開始,我希望能夠在每個方向(上,下,左,右和對角線)移動。 在代碼中,如何在各個方向遍歷數組,直到找到0?
我的理論思路是依次遍歷各個方向。 例如,從上升開始,所以我將檢查2上方的所有值
1
1
2
由於我沒有找到零,因此請檢查右上角的對角線
1
1
2
仍然沒有0,因此請轉到右側。 一旦找到我的第一個0,就休息。
嘗試:我實際上知道如何通過一堆if和for循環來做到這一點,但是我正在尋找一種方法來將該代碼編輯為更簡單易讀的版本
但是我是Java的新手,所以我不知道解決此問題的最佳方法。 有任何想法嗎?
TwoD Iterator顯然是一個不錯的開始。 我希望您可以自己做剩下的事,而無需付出很多努力。
在您的場景中找到第一個零將涉及遍歷每個Direction
並在該方向上遍歷整個迭代,直到迭代結束或您找到零為止。
進行螺旋搜索將涉及在每個方向上啟動迭代器,並執行一個步驟並依次檢查每個迭代器,直到一個返回可找到零的點為止。
public class TwoDIteratorTest {
// An ubiquitous Point class
static class Point {
final int x;
final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "{" + x + "," + y + "}";
}
}
// All possible directions.
enum Direction {
North(0, 1),
NorthEast(1, 1),
East(1, 0),
SouthEast(1, -1),
South(0, -1),
SouthWest(-1, -1),
West(-1, 0),
NorthWest(-1, 1);
private final int dx;
private final int dy;
Direction(int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
// Step that way
public Point step(Point p) {
return new Point(p.x + dx, p.y + dy);
}
}
static class TwoDIterator implements Iterable<Point> {
// Where we are now
Point i;
// Direction to move in.
private final Direction step;
// Limits.
private final Point min;
private final Point max;
// Next position to go to.
Point next = null;
// Normal constructor.
public TwoDIterator(Point start, Direction step, Point min, Point max) {
i = next = start;
this.step = step;
this.min = min;
this.max = max;
}
// Some simplified constructors
public TwoDIterator(int x, int y, Direction step, Point min, Point max) {
this(new Point(x, y), step, min, max);
}
public TwoDIterator(int x, int y, Direction step, int minx, int miny, int maxx, int maxy) {
this(new Point(x, y), step, new Point(minx, miny), new Point(maxx, maxy));
}
// The iterator.
@Override
public Iterator<Point> iterator() {
return new Iterator<Point>() {
// hasNext calculates next if necessary and checks it against the stabliched limits.
@Override
public boolean hasNext() {
if (next == null) {
// Step one.
next = step.step(i);
// Stop at limits.
if (next.x < min.x
|| next.x > max.x
|| next.y < min.y || next.y > max.y) {
next = null;
}
}
return next != null;
}
@Override
public Point next() {
if (hasNext()) {
// Make our move.
i = next;
next = null;
return i;
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
};
}
}
public void test() {
// Test all directions.
for (Direction d : Direction.values()) {
System.out.print(d + " - ");
for (Point p : new TwoDIterator(0, 0, d, -5, -5, 5, 5)) {
System.out.print(p + ",");
}
System.out.println();
}
}
public static void main(String[] args) throws InterruptedException {
new TwoDIteratorTest().test();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.