발효홍삼
코딩하는 홍삼
발효홍삼
전체 방문자
오늘
어제
  • 분류 전체보기 (142)
    • PS (63)
      • 프로그래머스 (9)
      • 코드업 (10)
      • 백준 (43)
      • 알고스팟 (1)
    • Programming Language (11)
      • html_css (2)
      • java (0)
      • c,c++ (2)
      • vanillajs (2)
      • react (0)
      • vue.js (0)
      • angular.js (0)
      • electron (3)
      • 엄랭(Umjunsik-lang) (1)
      • F# (1)
      • Node.js (0)
      • Go (0)
    • knowledge (41)
      • algorithm (3)
      • data structure (1)
      • os (1)
      • ML (1)
      • math (31)
      • paper review (0)
      • IT-license (4)
    • Programming Guide (27)
      • React (1)
      • Electron (2)
      • CSS , SASS ( SCSS ) , Tailw.. (3)
      • Node.js (1)
      • Go (1)
      • Ruby on Rails (2)
      • R (1)
      • PHP (1)
      • Docker (1)
      • JSP (1)
      • C# (1)
      • Django (1)
      • Flask (1)
      • Dart (1)
      • Next.js (1)
      • Vue.js (1)
      • Unity (1)
      • React Native (0)
      • Flutter (3)
      • GraphQL (1)
      • MongoDB (1)
      • .NET (1)
      • RUST (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Python
  • 미적분학
  • 미분
  • electron
  • CSS
  • codeup
  • cpp
  • 기초백제
  • HTML
  • 백준
  • c++
  • 이산수학
  • C
  • 구현
  • 정보처리기능사 필기
  • 기초100제
  • 수학
  • java
  • 출력
  • 알고리즘
  • js
  • JavaScript
  • LV1
  • 프로그래머스
  • 파이썬
  • 정보처리기능사
  • 자바
  • 코드업
  • 적분
  • nodejs

최근 댓글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
발효홍삼

코딩하는 홍삼

[ 백준 ] 7576번 : 토마토 - (c++/c, java/자바, python/파이썬)
PS/백준

[ 백준 ] 7576번 : 토마토 - (c++/c, java/자바, python/파이썬)

2022. 2. 14. 12:34
728x90
  • 문제

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net


  • 알고리즘 ( 접근 )

bfs 알고리즘을 통해 이미 익은 토마토의 상하좌우 방향을 탐색하고 익지 않은 토마토가 있는 좌표라면  현재 좌표를 익은 토마토로 바꿔준다.

bfs 알고리즘이 끝난 후 익지 않은 토마토가 하나라도 존재한다면 -1을 출력한다.


  • 풀이 - C++ ( C )
더보기
더보기
#include <stdio.h>
#include <queue>
#define MAX 1000

using namespace std;

int dX[4] = {-1, 1, 0, 0}; // 상 하 좌 우
int dY[4] = { 0, 0, -1, 1};

int main()
{
    int tomato[MAX][MAX] = { 0 };
    int visit[MAX][MAX] = { 0 };
    int m,n,i,j;
    int cnt = 0,ans = 1;
    int x,y,X,Y;
    queue<pair<pair<int,int>,int>> Q;

    scanf("%d %d", &m, &n);

    for(i=0;i<n;i++)
    {
         for(j=0;j<m;j++)
         {
            scanf("%d", &tomato[i][j]);
            if(tomato[i][j] == 1)
            {
                Q.push({{i,j},cnt});
            }
         }
    }


    while(!Q.empty())
    {
        x = Q.front().first.first;
        y = Q.front().first.second;
        cnt = Q.front().second;
        Q.pop();

        for(i=0;i<4;i++)
        {
            X = x + dX[i];
            Y = y + dY[i];

            if(X < n && Y < m && X >= 0 & Y >= 0 && visit[X][Y] == 0)
            {
                if(tomato[X][Y] == 0)
                {
                    Q.push({{X,Y},cnt+1});
                    visit[X][Y] = 1;
                    tomato[X][Y] = 1;
                }
            }
        }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {
            if(tomato[i][j] == 0)
            {
                printf("-1");
                return 0;
            }
        }
    }

    printf("%d", cnt);
    return 0;
}
  • 풀이 - JAVA
더보기
더보기

import java.util.*;
import java.io.*;

class node {
	int x;
	int y;
	
	node(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

public class Main {
	static int[] dx = {0,0,1,-1};
	static int[] dy = {1,-1,0,0};
	static int[][] tomato;
	static Queue<node> Q;
	
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int m = sc.nextInt();
		int n = sc.nextInt();
		
		tomato = new int[n][m];
		Q = new LinkedList<node>();
		
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
				tomato[i][j] = sc.nextInt();
				if(tomato[i][j] == 1) Q.add(new node(i,j));
			}
		}
		
		while(!Q.isEmpty())
		{
			node now = Q.remove();
			int x = now.x;
			int y = now.y;
			
			for(int i = 0; i < 4; i++)
			{
				int nx = x + dx[i];
				int ny = y + dy[i];
				
				if(nx >= 0 && ny >= 0 && nx < n && ny < m) {
					if(tomato[nx][ny] == 0) {
						Q.add(new node(nx,ny));
						tomato[nx][ny] = tomato[x][y] + 1;
					}
				}
			}
		}
		
		int ans = -12345678;
		
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
				if(tomato[i][j] == 0) 
				{
					System.out.print("-1");
					System.exit(0);
				}
				ans = Math.max(ans, tomato[i][j]);
			}
		}
		
		System.out.print(ans-1);
	}
}
  • 풀이 - PYTHON
더보기
더보기
from collections import deque
from logging.handlers import QueueListener
m,n = map(int, input().split())
tomato = []
Q = deque([])
dx = [1,-1,0,0]
dy = [0,0,1,-1]

for i in range(n):
    tomato.append(list(map(int,input().split())))
    for j in range(m):
        if tomato[i][j] == 1:
            Q.append([i,j])

while Q:
    x,y = Q.popleft()

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]

        if 0 <= nx <n and 0 <= ny < m and tomato[nx][ny] == 0:
            Q.append([nx,ny])
            tomato[nx][ny] = tomato[x][y] + 1

result = 0
for i in range(n):
    for j in range(m):
        if tomato[i][j] == 0:
            print(-1)
            exit(0)
        result = max(result, tomato[i][j])
print(result-1)

 

 

728x90
저작자표시 비영리 (새창열림)

'PS > 백준' 카테고리의 다른 글

[ 백준 ] 2302번 : 극장 좌석 - (c++/c, java/자바, python/파이썬)  (0) 2022.02.17
[ 백준 ] 1904번 : 01타일 - (c++/c, java/자바, python/파이썬)  (0) 2022.02.17
[ 백준 ] 1271번 : 엄청난 부자2 - (python/파이썬, java/자바)  (0) 2022.02.02
[ 백준 ] 1004번 : 어린 왕자 - (c++, c, python/파이썬, java/자바)  (0) 2022.01.28
[백준] 1003번 : 피보나치 함수 - (c++, c, python/파이썬, java/자바)  (0) 2022.01.28
    'PS/백준' 카테고리의 다른 글
    • [ 백준 ] 2302번 : 극장 좌석 - (c++/c, java/자바, python/파이썬)
    • [ 백준 ] 1904번 : 01타일 - (c++/c, java/자바, python/파이썬)
    • [ 백준 ] 1271번 : 엄청난 부자2 - (python/파이썬, java/자바)
    • [ 백준 ] 1004번 : 어린 왕자 - (c++, c, python/파이썬, java/자바)
    발효홍삼
    발효홍삼
    코딩하는 홍삼

    티스토리툴바