CS/Algorithm

[Python/Java] 백준 10709번: 기상캐스터

코드스피드 2025. 5. 21. 21:27
반응형

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

 

 

 

[설명]

 

기본적으로 구름이 절대 올 수 없는 곳에 대해 연산을 하지 않기위해 -1로 초기화해두었다.

그 다음, 구름이 처음 위치한 곳에 대해서 0으로 초기화 하고, 그 다음 동쪽으로 한 칸씩 이동해가며 다음 구름을 만나기 전까지

이전 상태에 대비해서 +1씩 값을 추가하여 갱신해나갔다.

 

여기서, 이전 값을 확인해야하므로, 최소한 j의 인덱스를 1 이상부터 비교해야 -1 위치인 0 인덱스와 비교할 수 있기 때문에 if문 조건식을 추가했다.

 

단순한 구현문제.

 

 

[코드]

- Python

h, w = map(int, input().split())
cloud = [list(input()) for _ in range(h)]
result = [[-1] * w for _ in range(h)]

for i in range(h):
    for j in range(w):
        if cloud[i][j] == 'c':
            result[i][j] = 0
        elif j > 0 and result[i][j - 1] >= 0:
            result[i][j] = result[i][j - 1] + 1

for i in range(h):
    print(*result[i])

 

 

- Java

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

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        StringBuilder sb = new StringBuilder();

        int h = Integer.parseInt(st.nextToken());
        int w = Integer.parseInt(st.nextToken());

        char[][] cloud = new char[h][w];
        int[][] result = new int[h][w];

        for (int i = 0; i < h; i++) {
            cloud[i] = br.readLine().toCharArray();
            Arrays.fill(result[i], -1);
        }

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if (cloud[i][j] == 'c') {
                    result[i][j] = 0;
                } else if (j > 0 && result[i][j - 1] >= 0) {
                    result[i][j] = result[i][j - 1] + 1;
                }
            }
        }

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                sb.append(result[i][j]).append(" ");
            }
            sb.append("\n");
        }

        System.out.println(sb);
    }
}

 

 

 

 

[시간복잡도]

O(N^2)

반응형