JAVA基础-在一个类中创建另一个类当结构体用的方法

方法就是将两个类写在同一个.java文件中,在实际项目中很少看到这样写,主要是在力扣刷题中偶尔会用到,比如新创建一个简单类当作结构体用,类中存放一些节点数据

力扣“934.最短的桥”就用到了这样的方法

class Solution {
    public int shortestBridge(int[][] A) {
        int R = A.length, C = A[0].length;
        int[][] colors = getComponents(A);

        Queue<Node> queue = new LinkedList();
        Set<Integer> target = new HashSet();

        for (int r = 0; r < R; ++r)
            for (int c = 0; c < C; ++c) {
                if (colors[r][c] == 1) {
                    queue.add(new Node(r, c, 0));
                } else if (colors[r][c] == 2) {
                    target.add(r * C + c);
                }
            }

        while (!queue.isEmpty()) {
            Node node = queue.poll();
            if (target.contains(node.r * C + node.c))
                return node.depth - 1;
            for (int nei: neighbors(A, node.r, node.c)) {
                int nr = nei / C, nc = nei % C;
                if (colors[nr][nc] != 1) {
                    queue.add(new Node(nr, nc, node.depth + 1));
                    colors[nr][nc] = 1;
                }
            }
        }

        throw null;
    }


        //balabalabala
        //省略其他代码,主要展示怎样在一个文件中写两个类
}


//此处另一个类Node的声明就是直接在Solution类定义结束后在下面在定义一个类,因为都是同一个文件下可以直接被调用
class Node {
    int r, c, depth;
    Node(int r, int c, int d) {
        this.r = r;
        this.c = c;
        depth = d;
    }
}

 


版权声明:本文为m0_37965811原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。