자료구조와 알고리듬 With Java/[Study] BAEKJOON 프로그래머스 CodeUp LeetCode
Code up 4572 영역 구하기 / 오류 수정하기
계란💕
2022. 4. 24. 17:13
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)