-
[JAVA] SWEA 탈주범 검거알고리즘 공부/문제 풀이 2021. 9. 30. 21:14
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); for(int t=1; t<=T; t++) { StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); int R = Integer.parseInt(st.nextToken()); int C = Integer.parseInt(st.nextToken()); L = Integer.parseInt(st.nextToken()); map = new int[N][M]; visit = new int[N][M]; for(int i=0;i<N;i++) { st = new StringTokenizer(br.readLine()); for(int j=0;j<M;j++) map[i][j] = Integer.parseInt(st.nextToken()); Arrays.fill(visit[i], Integer.MAX_VALUE); } dfs(R, C, 0); int ans = 0; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { if(visit[i][j]<=L) ans++; } } System.out.println("#"+t+" "+ans); } } static int N, M, L; static int[][] map; static int[][] visit; static int[][][] pipe = {{{-1,1,0,0}, {0,0,-1,1}}, {{-1,1},{0,0}}, {{0,0},{-1,1}}, {{-1,0},{0,1}}, {{1,0},{0,1}}, {{1,0},{0,-1}}, {{-1,0},{0,-1}}}; public static void dfs(int r, int c, int time) { if(time==L) return; visit[r][c] = time; int p = map[r][c]-1; for(int i=0; i< pipe[p][0].length;i++) { int nr = r + pipe[p][0][i]; int nc = c + pipe[p][1][i]; if(0<=nr && nr<N && 0<=nc && nc<M && visit[nr][nc]>time && canGo(nr-r, nc-c, map[nr][nc]-1) ) { dfs(nr, nc, time+1); } } } public static boolean canGo(int dr, int dc, int p) { if(p<0) return false; for(int i=0; i< pipe[p][0].length;i++) { if(pipe[p][0][i]==(dr*-1) && pipe[p][1][i]==(dc*-1)) return true; } return false; } }
'알고리즘 공부 > 문제 풀이' 카테고리의 다른 글
[JAVA] SWEA 4014 활주로 건설 (0) 2021.10.06 [JAVA] 백준 17471 게리맨더링 (0) 2021.10.06 [JAVA] SWEA 보급로 (0) 2021.09.30 [JAVA] 백준 2357 최솟값과 최댓값 (0) 2021.09.29 [JAVA] 백준 20056 마법사 상어와 파이어 볼 (0) 2021.09.29