Article Image
Article Image
read
문제
1953. [모의 SW 역량테스트] 탈주범 검거
풀이
이 문제는 BFS 알고리즘을 이용해서 풀 수 있었고 현재 터널의 모양과 앞으로 나아갈 방향의 통로를 모두 고려해야 한다.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Queue;
import java.util.LinkedList;
class Solution {
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static int N;
static int M;
static int L;
static int[][] map;
static int ans;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int test_case = 1; test_case <= T; test_case++)
{
String[] input = br.readLine().split(" ");
N = Integer.parseInt(input[0]);
M = Integer.parseInt(input[1]);
int R = Integer.parseInt(input[2]);
int C = Integer.parseInt(input[3]);
L = Integer.parseInt(input[4]);
map = new int[N][M];
ans = 0;
for(int i=0; i<N; i++) {
input = br.readLine().split(" ");
for(int j=0; j<M; j++) {
map[i][j] = Integer.parseInt(input[j]);
}
}
bfs(R, C);
System.out.println("#"+test_case+" "+ans);
}
}
public static void bfs(int x, int y) {
Queue<Pair> queue = new LinkedList<>();
boolean[][] visited = new boolean[N][M];
visited[x][y] = true;
queue.add(new Pair(x, y, 1));
while(!queue.isEmpty() && queue.peek().t<=L) {
ans++;
Pair p = queue.poll();
for(int i=0; i<4; i++) {
if(i==0 && (map[p.x][p.y]==3 || map[p.x][p.y]==5 || map[p.x][p.y]==6)) continue;
if(i==1 && (map[p.x][p.y]==3 || map[p.x][p.y]==4 || map[p.x][p.y]==7)) continue;
if(i==2 && (map[p.x][p.y]==2 || map[p.x][p.y]==4 || map[p.x][p.y]==5)) continue;
if(i==3 && (map[p.x][p.y]==2 || map[p.x][p.y]==6 || map[p.x][p.y]==7)) continue;
int nx = p.x+dx[i];
int ny = p.y+dy[i];
if(nx<0 || nx>=N || ny<0 || ny>=M || visited[nx][ny] || map[nx][ny]==0) continue;
if(i==0 && (map[nx][ny]==3 || map[nx][ny]==4 || map[nx][ny]==7)) continue;
if(i==1 && (map[nx][ny]==3 || map[nx][ny]==5 || map[nx][ny]==6)) continue;
if(i==2 && (map[nx][ny]==2 || map[nx][ny]==6 || map[nx][ny]==7)) continue;
if(i==3 && (map[nx][ny]==2 || map[nx][ny]==4 || map[nx][ny]==5)) continue;
visited[nx][ny] = true;
queue.add(new Pair(nx, ny, p.t+1));
}
}
}
public static class Pair {
int x;
int y;
int t;
public Pair(int x, int y, int t) {
this.x = x;
this.y = y;
this.t = t;
}
}
}