on
Java floodfill2
Java floodfill2
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 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); }
공유하기 글 요소 저작자표시
from http://nahyungmin.tistory.com/270 by ccl(A) rewrite - 2021-12-16 12:01:24