백준 To and Fro

KIMYEONGJUN·2026년 2월 16일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

There will be multiple input sets.
Input for each set will consist of two lines.
The first line will contain an integer in the range 2 . . . 20 indicating the number of columns used.
The next line is a string of up to 200 lower case letters.
The last input set is followed by a line containing a single 0, indicating end of input.

Each input set should generate one line of output, giving the original plaintext message, with no spaces.

내가 이 문제를 보고 생각해본 부분

BufferedReader로 입력을 빠르게 받는다.
우선 무한 루프를 돌면서 열 수를 읽는다.
0이면 while문 종료로 프로그램 끝낸다.
암호문 길이를 열 수로 나누면 행 수가 나온다.
암호화된 문자열을 행별로 substring하며 나눈다.
행 번호가 짝수이면(0부터 시작하므로 첫 행은 0) 행 방향 그대로 저장한다.
행 번호가 홀수이면 해당 행은 오른쪽에서 왼쪽으로 암호화했으므로 문자열을 뒤집어서 저장한다.
이렇게 만든 2차원 문자 배열에서 열 단위로 위에서 아래로 읽으면 원래 메시지를 얻는다.
마지막으로 복원된 문자열을 출력한다.
마지막에 리소스 누수를 막기 위해 br.close()로 스트림을 닫는다.

코드로 구현

package baekjoon.baekjoon_32;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 백준 4246번 문제
public class Main1300 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            int cols = Integer.parseInt(br.readLine());
            if (cols == 0)
                break;

            String encrypted = br.readLine();
            int rows = encrypted.length() / cols;
            char[][] matrix = new char[rows][cols];

            // 행별로 문자 분리
            for (int i = 0; i < rows; i++) {
                String rowStr = encrypted.substring(i * cols, (i + 1) * cols);
                // 홀수 행 (0-based idx 짝수) 왼->오 그대로 저장
                if (i % 2 == 0) {
                    for (int j = 0; j < cols; j++) {
                        matrix[i][j] = rowStr.charAt(j);
                    }
                } else { // 짝수 행 (0-based idx 홀수) 오른->왼으로 저장 (뒤집기)
                    for (int j = 0; j < cols; j++) {
                        matrix[i][j] = rowStr.charAt(cols - 1 - j);
                    }
                }
            }

            // 열별로 읽기 -> 원래 메시지 복원
            StringBuilder sb = new StringBuilder();
            for (int c = 0; c < cols; c++) {
                for (int r = 0; r < rows; r++) {
                    sb.append(matrix[r][c]);
                }
            }

            System.out.println(sb.toString());
        }
        br.close();
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글