๋ฌธ์ :
https://www.acmicpc.net/problem/7576
๋ถ์ :
์ด๋ฐ์์ผ๋ก ํ ๋งํ ๋์ฅ์ด ์กด์ฌ ํ ๋
1์ ์ต์ ํ ๋งํ , ์ ์ 0์ ์ต์ง ์์ ํ ๋งํ , ์ ์ -1์ ํ ๋งํ ๊ฐ ๋ค์ด์์ง ์์ ์นธ
์ ์๋ฏธํ๋ค.
์ต์ ํ ๋งํ ์ค์ฌ์ผ๋ก ์ํ์ข์ฐ๋ก ํ๋ฃจ๋ง๋ค ํ ๋งํ ๊ฐ ์ต๋๋ฐ ๋ช์ผ์ด๋ฉด ๋์ฅ ๋ด ๋ชจ๋ ํ ๋งํ ๊ฐ ์ต๋์ง ๋ ์ง๋ฅผ ์ถ๋ ฅํ๋ ๋ฌธ์ ์๋ค.
์ฐ์ ํ ๋งํ ๋์ฅ์ ํ์ํ๋ค๋ ์ ์์ BFS, DFS๋ก ์ ๊ทผํด์ผ ํ๋ค ์๊ฐํ๊ณ ํ์์ ํ๋ฉด์ ๋ฐฉ๋ฌธํ์ง ์์๋ 0์ for๋ฌธ์ ๋๋ฉด์ 1์ฉ ๋๋ ค ์ฃผ๊ณ ๋ชจ๋ 0์ด 1๋ก ๋ฐ๋์์๋ dfs ํ์์ ํตํด ๋ ์ง๋ฅผ ๊ณ์ฐํ๋๋ก ํ์๋ค.
//
// 7576_tomato.cpp
// SOMA๐ฉ๐ป๐ป
//
// Created by JoSoJeong on 2021/04/22.
//
#include <stdio.h>
#include <queue>
#include <iostream>
using namespace std;
int tomatoMap[1001][1001];
int M, N;
int tomatoCount;
int dfscount;
int visit[1001][1001] = {false, };
int dx[] = { 0, 0, 1, -1 }; //up down left right
int dy[] = { 1, -1, 0, 0 };
queue<pair<int, int>> s;
void tomato_dfs(){
while(!s.empty()){
pair<int, int> cur = s.front();
s.pop();
for(int i = 0; i < 4; i++){
int nextX = cur.first + dx[i];
int nextY = cur.second + dy[i];
if(nextX < N && nextY < M && nextX >= 0 && nextY >= 0 ){
if(visit[nextX][nextY] == false && tomatoMap[nextX][nextY] == 0){
visit[nextX][nextY] = true;
s.push({nextX, nextY});
dfscount++;
tomatoMap[nextX][nextY] = tomatoMap[cur.first][cur.second] + 1;
}
}
}
}
}
int main(){
cin >> M >> N; // 6 4
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cin >> tomatoMap[i][j];
if(tomatoMap[i][j] == 0){ // tomato count
tomatoCount++;
}else if(tomatoMap[i][j] == 1){
s.push({i,j});
//startPoint = make_pair(i,j);
}
}
}
int max = 0;
if(tomatoCount == 0){
cout << "0" << '\n'; // ๋ชจ๋ ํ ๋งํ ์ต์ด์๋ ์ํ
return 0;
}else{
tomato_dfs();
if(tomatoCount - dfscount != 0){ // ํ ๋งํ ๋ค ์ต์ง x
cout << "-1" << '\n';
return 0;
}
for(int i = 0; i < N; i++){ // ํ ๋งํ ๋ค ์ตํ
for(int j = 0; j < M; j++){
if(max < tomatoMap[i][j]){
max = tomatoMap[i][j];
}
}
}
cout << max - 1 << '\n';
}
return 0;
}
๋ง์ง๋ง ํ ๋งํ ์ต์ ๋ ์ง๋ฅผ ๊ตฌํ๊ธฐ ์ํด ์ด์ค for๋ฌธ์ผ๋ก max ๊ฐ์ ์ฐพ๋ ๋ถ๋ถ์ด ๋นํจ์จ์ ์ผ๋ก ๋ณด์ธ๋ค. ์ด๋ถ๋ถ์ ์์ ํด๋ณด์์ผ๊ฒ ๋ค.
'Algorithm๐ฐ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 1018 ์ฒด์คํ ๋ค์ ์น ํ๊ธฐ brute force (0) | 2022.02.17 |
---|---|
[๋ฐฑ์ค] 1969 DNA (0) | 2022.02.16 |
[๋ฐฑ์ค] 15681 ํธ๋ฆฌ์ ์ฟผ๋ฆฌ DP + DFS (0) | 2021.09.09 |
[๋ฐฑ์ค] 1463 1๋ก ๋ง๋ค๊ธฐ DP (0) | 2021.08.23 |
[๋ฐฑ์ค] 5567 ๊ฒฐํผ์ ๊ตฌํ (0) | 2021.06.13 |
๋๊ธ