반응형
BackJoon
#7576 - 토마토(Tomato)
https://www.acmicpc.net/problem/7576
백준 쉬운 토마토 문제 BFS로 돌리면 쉽게 해결 할 수 있습니다. ㅎㅎ
package BackJoon.Graph.BFS;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Tomato2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] array = new int[n][m];
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
array[i][j] = sc.nextInt();
}
}
//print(array);
solution(array);
}
static int goX[] = {-1, 0, 0, 1};
static int goY[] = {0, -1, 1, 0};
private static void solution(int[][] array) {
int n = array.length;
int m = array[0].length;
Queue<Point> queue = new LinkedList<>();
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
if(array[i][j] == 1)
queue.add(new Point(i, j));
}
}
while(!queue.isEmpty()){
Point current = queue.poll();
for(int i=0; i<4; i++){
int x = current.x + goX[i];
int y = current.y + goY[i];
if(-1 < x && x < n && -1 < y && y < m && array[x][y] == 0){
array[x][y] = array[current.x][current.y] + 1;
queue.add(new Point(x,y));
}
}
}
//print(array);
int temp = array[0][0];
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
if(temp < array[i][j]){
temp = array[i][j];
}
if(array[i][j] == 0){
System.out.println("-1");
return;
}
}
}
System.out.println(temp-1);
}
public static void print(int [][]array){
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
System.out.print(array[i][j]+" ");
}
System.out.println("");
}
}
}
반응형
'Algorithm > BackJoon' 카테고리의 다른 글
| [삼성SW테스트] 드래곤 커브 15685(백준) (3) | 2018.06.23 |
|---|---|
| [삼성SW테스트] 치킨배달 15686(백준) (0) | 2018.06.16 |
| [Recursion] 하노이(Hanoi) (2) | 2018.01.21 |
| [DFS] 경로찾기(Find Directions) (0) | 2017.11.22 |
| [삼성SDS] 백준 - 경사로(Runway) (0) | 2017.11.08 |
댓글