본문 바로가기
알고리즘

Java floodfill

by NaHyungMin 2021. 12. 15.
final static int[] xArray = {1, 0, -1, 0};
final static int[] yArray = {0, 1, 0, -1};

  public static class Node {
    int x;
    int y;

    public Node(int x, int y) {
      this.x = x;
      this.y = y;
    }

    public void setX(int x) { this.x = x; }
    public void setY(int y) { this.y = y; }

    public int getX() { return this.x; }
    public int getY() { return this.y; }
  }

  public static void main(String[] args) {
    floodFill();
  }

  private static void floodFill() {
    int arrayLength = xArray.length;
    int n = 7;
    int m = 10;
    int board[][] =
            {
                    {1, 1, 1, 0, 1, 0, 0, 0, 0, 0},
                    {1, 0, 0, 0, 1, 0, 0, 0, 0, 0},
                    {1, 1, 1, 0, 1, 0, 0, 0, 0, 0},
                    {1, 1, 0, 0, 1, 0, 0, 0, 0, 0},
                    {0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
                    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
            };

    boolean[][] visited = new boolean[n][m];
    Queue<Node> queue = new LinkedList<>();

    visited[0][0] = true;
    queue.add(new Node(0, 0));

    while (!queue.isEmpty()) {
      Node node = queue.poll();
      System.out.println("x : " + node.getX() + " y : " + node.getY());

      for(int i = 0; i < arrayLength; i++) {
        int x = node.getX() + xArray[i];
        int y = node.getY() + yArray[i];

        if(x < 0 || x >= n || y < 0 || y >= m) {
          continue;
        }

        if(visited[x][y] || board[x][y] != 1) {
          continue;
        }

        visited[x][y] = true;
        queue.add(new Node(x, y));
      }
    }
  }

 

다른 분이 c++로 구현한걸 java로 옮김.

출처

https://blog.encrypted.gg/941

 

'알고리즘' 카테고리의 다른 글

Java 토마토  (0) 2021.12.20
Java 미로찾기  (0) 2021.12.17
Java floodfill2  (0) 2021.12.16
백준 #1712: 손익분기점  (0) 2021.11.03