Java 迭代二维数组

标签 java arrays multidimensional-array iteration

我有一个 Java 中的二维数组,如下所示:

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新手,所以我不知道解决这个问题的最佳方法。有什么想法吗?

最佳答案

二维迭代器显然是一个好的开始。我希望您可以毫不费力地完成剩下的事情。

找到场景中的第一个零需要迭代每个方向并沿该方向全面迭代,直到迭代结束或找到零。

进行螺旋搜索需要在每个方向上启动一个迭代器,然后执行一步并依次检查每个迭代器,直到返回一个可以找到零的点。

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();
    }
}

关于Java 迭代二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15604470/

相关文章:

php - 使用 PHP 从只读 Google 表格获取数据

Java : Why can't I declare an array as a simple Object?

java - 如何让我的程序检查页面上是否存在图标

java - 修复 JComboBox 宽度

java - 带有 DBCP BasicDataSource 的 Spring JdbcTemplate 仍然关闭连接

java - OAuth 2.0、Open ID 连接和 SAML

java - 如何在数组中找到总和为 k 的两个元素

java - JVM是怎么分配这 block 内存的

c++ - 填充动态数组时获取退出状态-1

java - 数组列表的重复条目