简体   繁体   English

Java遍历2D数组

[英]Java Iterating Through 2D-Array

I have a 2D array in Java like so: 我在Java中有一个2D数组,如下所示:

int 2d_arr[5][5];

Take, for example, the board that looks like this: 以如下所示的板子为例:

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

Starting from the 2 in the 3rd row, I want to be able to move in every direction (Up, down, left, right, and diagonals). 从第三行的2开始,我希望能够在每个方向(上,下,左,右和对角线)移动。 In code, how do I traverse the array in every direction till I find a 0? 在代码中,如何在各个方向遍历数组,直到找到0?

My theoretical idea would be to iterate in every direction sequentially. 我的理论思路是依次遍历各个方向。 For example, start by going up, so I would check all the values on the line above 2 例如,从上升开始,所以我将检查2上方的所有值

1
1
2

Since I didn't find any zeros, check the top right diagonal 由于我没有找到零,因此请检查右上角的对角线

   1
  1
 2

Still no 0s, so go onto the right. 仍然没有0,因此请转到右侧。 As soon as I find my first 0, break. 一旦找到我的第一个0,就休息。

Attempt: I actually know how to do to this with a bunch of if and for loops, but I am looking for a way to edit that code to a simpler and easier to read version 尝试:我实际上知道如何通过一堆if和for循环来做到这一点,但是我正在寻找一种方法来将该代码编辑为更简单易读的版本

But I'm new to java so I don't know the best way to go about this. 但是我是Java的新手,所以我不知道解决此问题的最佳方法。 Any ideas? 有任何想法吗?

A TwoD Iterator would obviously be a good start. TwoD Iterator显然是一个不错的开始。 I expect you could do the rest yourself without much effort. 我希望您可以自己做剩下的事,而无需付出很多努力。

Finding the first zero in your scenario would involve iterating through each Direction and iterating across the board in that direction until the iteration ends or you find your zero. 在您的场景中找到第一个零将涉及遍历每个Direction并在该方向上遍历整个迭代,直到迭代结束或您找到零为止。

Doing a spiral search would involve starting an iterator in each direction and doing a step and check on each one in turn until one returns a point where a zero can be found. 进行螺旋搜索将涉及在每个方向上启动迭代器,并执行一个步骤并依次检查每个迭代器,直到一个返回可找到零的点为止。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM