DFS의 개념이 필요한 문제였습니다.
다음에 다시 한번 보도록 해야겠습니다.
package com.company;
import java.util.Scanner;
public class boj14502version2 {
static int N, M,totalCNT;
static int[][] map, visited;
static int[] dx = {0, -1, 0, 1};
static int[] dy = {-1, 0, 1, 0};
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
map = new int[N][M];
visited = new int[N][M];
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
map[i][j] = sc.nextInt();
}
}
for(int i=0; i<N*M; i++){
int row = i/M;
int col = i%M;
if(map[row][col] == 0){
map[row][col] = 1;
DFS(i, 1);
map[row][col] = 0;
}
}
System.out.println(totalCNT);
}
static void DFS(int v, int cnt){
int row = v/M;
int col = v%M;
if(cnt == 3){
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
visited[i][j] = map[i][j];
}
}
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
if(visited[i][j] == 2){
spreadVirus(i,j);
}
}
}
safetyArea();
} else {
for(int i=v+1; i<N*M; i++){
int row2 = i/M;
int col2 = i%M;
if(map[row2][col2] == 0){
map[row2][col2] = 1;
DFS(i, cnt+1);
}
}
}
map[row][col] = 0;
}
static void spreadVirus(int row, int col) {
for(int i=0; i<4; i++) {
int nextRow = dx[i]+row;
int nextCol = dy[i]+col;
if(nextRow>=0 && nextRow<N && nextCol>=0 && nextCol<M) {
if(visited[nextRow][nextCol]==0) {
visited[nextRow][nextCol]=2;
spreadVirus(nextRow, nextCol);
}
}
}
}
//안정 영역 크기 구하기
static void safetyArea() {
int cnt=0;
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
if(visited[i][j]==0) {
cnt++;
}
}
}
if(totalCNT<cnt) {
totalCNT = cnt;
}
}
}
'알고리즘' 카테고리의 다른 글
SWEA - 벌꿀채취 (0) | 2020.05.11 |
---|---|
백준 - 14503 로봇청소기(삼성 SW 기출) (0) | 2020.05.02 |
백준 14889 - 스마트와 링크 (0) | 2020.04.26 |
백준 17144번 - 미세먼지 안녕!(런타임 에러) (0) | 2020.04.26 |
프로그래머스 - 구명보트 (0) | 2020.04.17 |