[Algorithm/Java] 백준 10709번 - 기상캐스터
https://www.acmicpc.net/problem/10709
🔍 문제 풀이
Flowchart
💻 전체 코드
-1 센티널 사용
cloudCol == 0
으로 초기화하면, 실제로 첫 구름이 0번 열에 있는 경우와 구분이 안 됨.- 따라서
-1
로 초기화하여 첫 구름 전에는 -1 그대로 유지되다가, 구름 만나면 위치값으로 변경되도록 해야함
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 입력 및 초기화
StringTokenizer st = new StringTokenizer(br.readLine());
int h = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
char[][] arr = new char[h][w];
int[][] result = new int[h][w];
for(int i=0; i<h; i++){
String line= br.readLine();
for(int j=0; j<w; j++){
arr[i][j] = line.charAt(j);
}
}
// 계산
for(int i=0; i<h; i++){
int cloudCol = -1; // 주의
for(int j=0; j<w; j++){
if(arr[i][j] == 'c'){
result[i][j] = 0;
cloudCol = j;
}else {
if (cloudCol == -1) result[i][j] = -1;
else result[i][j] = j - cloudCol;
}
}
}
// 출력
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
boolean 분리
cloudCol은 마지막 구름 위치만 저장하고, 본 적 있는지 여부는 boolean seen으로 별도 관리
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 입력 및 배열 초기화
StringTokenizer st = new StringTokenizer(br.readLine());
int h = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
char[][] arr = new char[h][w];
int[][] result = new int[h][w];
for(int i=0; i<h; i++){
String line= br.readLine();
for(int j=0; j<w; j++){
arr[i][j] = line.charAt(j);
}
}
// 계산
for(int i=0; i<h; i++){
int cloudCol = 0;
boolean seen = false;
for(int j=0; j<w; j++){
if(arr[i][j] == 'c'){
result[i][j] = 0;
cloudCol = j;
seen = true;
}else {
result[i][j] = seen ? (j - cloudCol) : -1;
}
}
}
// 출력
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
댓글남기기