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 = 6;
int m = 5;
int board[][] =
{
{1, 1, 0, 1, 1},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
{1, 0, 1, 1, 1},
{1, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1}
};
boolean[][] visited = new boolean[n][m];
int maxImageCount = 0;
int imageCount = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(board[i][j] == 0 || visited[i][j]) {
continue;
}
imageCount++;
Queue<Node> queue = new LinkedList<>();
visited[i][j] = true;
queue.add(new Node(i, j));
int area = 0;
while (!queue.isEmpty()) {
area++;
Node node = queue.poll();
for(int k = 0; k < arrayLength; k++) {
int x = node.getX() + xArray[k];
int y = node.getY() + yArray[k];
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));
}
}
if(area > maxImageCount) {
maxImageCount = area;
}
}
}
System.out.println("총 이미지 수 : " + imageCount);
System.out.println("최대 보유 이미지 수 : " + maxImageCount);
}
'알고리즘' 카테고리의 다른 글
Java 토마토 (0) | 2021.12.20 |
---|---|
Java 미로찾기 (0) | 2021.12.17 |
Java floodfill (0) | 2021.12.15 |
백준 #1712: 손익분기점 (0) | 2021.11.03 |