如何使用' w'来计算网格中有多少个区域?在其中

时间:2017-10-13 23:23:39

标签: java multidimensional-array

我有一个程序,我在网格文件中阅读,只是' w'并且它的大小为10.我想知道我如何计算连接的白色(或w)有多少个区域以及w的数量是多少?在每个区域内。我有一个主要方法,一个读取网格的方法,一种计算整个网格中每个w的方法,但不知道如何计算区域以及如何指定每个区域中有多少白色。有人可以帮助我吗?

import java.io.File;
import java.util.Scanner;

public class program {
    private int xD[] = {0, 1, 1, 1, 0, -1, -1, -1};
    private int yD[] = {1, 1, 0, -1, -1, -1, 0, 1};

    public Program() {
        n = 0;
        k = 0;
        CountSpace = 0;
    }

    private char[][] getGrid() { //Takes in the grid, counts the number of squares
        String fileName = "grid.txt";
        try {
            File file = new File(fileName);
            Scanner input = new Scanner(file);
            String line = "";
            line = input.nextLine();
            line = line.replaceAll("\\s+", "");
            n = line.length();
            grid = new char[n][n];
            for (int y = 0; y < n; y++) {
                if (y > 0) {
                    line = input.nextLine();
                    line = line.replaceAll("\\s+", "");
                }
                for (int x = 0; x < n; x++) {
                    grid[x][y] = line.charAt(x);
                }
            }

            visited = new boolean[n][n];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    visited[i][j] = false;
                }
            }
            input.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        return grid;
    }

    private void display() //Displays the grid that was read in from the text file
    {
        System.out.println("Grid : ");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(grid[j][i] + " ");
            }
            System.out.println();
        }

        System.out.println();
        System.out.println("# Spaces: " + CountSpace);
    }

    public static void main(String[] args) //main method
    {
        Program p = new Program();
        char[][] temp = p.getGrid();
        p.display();
    }
}

1 个答案:

答案 0 :(得分:0)

您所描述的内容听起来像是在二进制图像中标记连接的组件。 https://en.m.wikipedia.org/wiki/Connected-component_labeling