Ex)
<hide/>
package first;
/*
5 7 3
0 2 4 4
1 1 2 5
4 0 6 2
*/
import java.util.Scanner;
public class CountTerritory {
static int Width;
static int Height;
static int MAX_COUNT = 101;
static int[][] VisitMatrix = new int[MAX_COUNT][MAX_COUNT];
static int[][] AdjMatrix = new int[MAX_COUNT][MAX_COUNT];
static int DIRECTION = 4;
static int[][] DirMatrix = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
static int cnt = 0;
static int[] AreaArr;
static int AreaCnt = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Height = scan.nextInt(); // 5
Width = scan.nextInt(); // 7
int K = scan.nextInt();
for(int i = 1; i <= K ; ++i ) {
int x1 = scan.nextInt();
int y1 = scan.nextInt();
int x2 = scan.nextInt();
int y2 = scan.nextInt();
for(int x = x1 + 1; x <= x2; ++x) {
for(int y = y1 + 1; y <= y2; ++y) {
AdjMatrix[x][y] = 1;
}
}
}
// 인접행렬 출력
for(int y = Height; y >= 1 ; --y) {
for(int x = 1; x <= Width; ++x) {
System.out.printf(AdjMatrix[x][y]+ " ");
}
System.out.println();
}
// 방문행렬 초기화
for(int i = 1; i<= Width; ++i) {
for(int j = 1; j <= Height; ++j) {
VisitMatrix[i][j] = 0;
}
}
// 인접행렬 출력
for(int y = Height; y >= 1 ; --y) {
for(int x = 1; x <= Width; ++x) {
if(0 == VisitMatrix[x][y] && 1 == AdjMatrix[x][y]) {
++cnt;
DFS1(x, y);
AreaArr[cnt - 1] = AreaCnt + 1;
AreaCnt = 0;
}
}
}
System.out.println(cnt);
for(int i = 0; i < cnt; ++i) {
System.out.println(AreaArr[i]);
}
}
public static void DFS1(int _CurrX, int _CurrY) {
VisitMatrix[_CurrX][_CurrY] = 1;
for(int i = 0; i < DIRECTION; ++i) {
int nextX = _CurrX + DirMatrix[i][0];
int nextY = _CurrY + DirMatrix[i][1];
if(1 == VisitMatrix[nextX][nextY]) continue;
if(1 == AdjMatrix[nextX][nextY] &&
1 <= nextX && nextX <= Width &&
1 <= nextY && nextY <= Height ) {
++AreaCnt;
DFS1(nextX, nextY);
}
}
}
}
Note)
'자료구조와 알고리듬 With Java > [Study] BAEKJOON 프로그래머스 CodeUp LeetCode' 카테고리의 다른 글
Java로 BFS 구현하기 (0) | 2022.04.28 |
---|---|
Code up 4060 전광판 전구 조작 (0) | 2022.04.24 |
Code up 4714 BAEKJOON 2458 키 순서 (0) | 2022.04.24 |
Code up 2605 캔디팡 (0) | 2022.04.22 |
DFS 촌수 찾기 (오류 수정 전) (0) | 2022.04.22 |