개발새발 로그

[JS] 백준 2363 : 치즈(2변이상이면 녹는 치즈) 본문

알고리즘

[JS] 백준 2363 : 치즈(2변이상이면 녹는 치즈)

이즈흐 2023. 7. 15. 14:11

https://www.acmicpc.net/problem/2638

 

2638번: 치즈

첫째 줄에는 모눈종이의 크기를 나타내는 두 개의 정수 N, M (5 ≤ N, M ≤ 100)이 주어진다. 그 다음 N개의 줄에는 모눈종이 위의 격자에 치즈가 있는 부분은 1로 표시되고, 치즈가 없는 부분은 0으로

www.acmicpc.net

 

📋풀이방법

1. 치즈 밖 공기부분 0을 2로바꾼다

2. 치즈부분들을 순회하면서 한 부분이 2를 상하좌우 2번이상만나는 곳은 2로 바꿔준다.

3. 2로 바꾼 곳을 다시 0으로 바꿔준다.(구멍이있는 치즈가 있으니까 뚫리면 그곳도 공기부분으로 만들기위해

4. 만약 치즈부분이없으면 멈춰준다.

 

🤟내 제출

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let input = fs.readFileSync(filePath).toString().trim();
input=input.replace(/\r/g,"").split("\n");

let [N,M]=input.shift().split(" ").map(Number);
let arr=[];
for(var i=0;i<N;i++){
    arr.push(input.shift().split(" ").map(Number));
}

let dx=[1,0,0,-1];
let dy=[0,1,-1,0];

function DFS(y,x){
	for(var i=0;i<4;i++){
		let nx=x+dx[i];
		let ny=y+dy[i];
		if(nx>=0 && ny>=0 && nx<M && ny<N && arr[ny][nx]==0){
			arr[ny][nx]=2
			DFS(ny,nx)
		}
	}
}
let answer=0;

while(1){
	let temp=[];
	for(var i=0;i<N;i++){
		for(var j=0;j<M;j++){
			if(arr[i][j]==1){
				temp.push([i,j]);
				
			}
		}
	}

	DFS(0,0)
	let arr_temp= arr.map(s=>[...s]);
	temp.forEach((tt)=>{
		let [y,x]=tt;
		let cnt=0;
		for(var i=0;i<4;i++){
			let nx=x+dx[i];
			let ny=y+dy[i];		
			if(nx>=0 && ny>=0 && nx<M && ny<N && arr[ny][nx]==2){
				cnt++;
				if(cnt>=2){
					arr_temp[y][x]=2;
					break;
				}
			}
		}
	})
	arr=arr_temp.map(v=>[...v]);
	let count=0;
    //2인곳을 0으로 바뀐 뒤에 0의 갯수를 세어야 안꼬임
    for(var i=0;i<N;i++){
        for(var j=0;j<M;j++){
            
            if(arr[i][j]==2){
                arr[i][j]=0;
                
            }
            if(arr[i][j]==0) count++;
            
        }
    }
	if(count==(N*M)) {
        answer++;
        break;
    }
	answer++;
}
console.log(answer)

 

 

이전 치즈문제와 거의 유사한 문제였다 

그 문제와는 2변이상이라는 조건만 달랐다.

 

728x90
반응형
LIST