[SWEA] 4875

ninano05·2026년 4월 1일

파이썬 문제라 채점은 못해봤다.
예제 테케만 확인함

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

public class Main {
    static int[][] miro;
    static int N;
    static int result;

    // 오른쪽 왼쪽 위 아래
    static int[] dRow = {1, -1, 0, 0};
    static int[] dCol = {0, 0, -1, 1};

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int T = Integer.parseInt(br.readLine());
        StringBuilder sb = new StringBuilder();
        int row=0; // 시작 행
        int col=0; // 시작 열

        for(int t=0; t<T; t++) {
            N = Integer.parseInt(br.readLine());
            miro = new int[N][N];

            // 미로 채우기
            for(int i=0; i<N; i++) {
                String s = br.readLine();
                for(int j=0; j<N; j++) {
                    miro[i][j] = s.charAt(j) - '0';
                    if(miro[i][j] == 2) {
                        row = i;
                        col = j;
                    }
                }
            }
            result = 0;
            dfs(row, col);
            sb.append("#").append(t).append(" ").append(result).append("\n");
        }
        bw.write(sb.toString());
        bw.flush();
        bw.close();
        br.close();
    }

    public static void dfs(int row, int col) {
        // 도착점 도달한 경우
        if(miro[row][col] == 3) {
            result = 1;
        }

        // 방문한 곳은 벽(1)로 만들기
        miro[row][col] = 1;

        for(int i=0; i<4; i++) {
            int nRow = row + dRow[i];
            int nCol = col + dCol[i];

            if(nRow < N && nRow >= 0 && nCol < N && nCol >= 0) {
                if(miro[nRow][nCol] != 1) {
                    dfs(nRow, nCol);
                }
            }
        }
    }
}
profile
초보 개발자

0개의 댓글