코드트리 문제풀이
네 방향 탈출 가능 여부 판별하기
import java.util.*;
public class Main {
static int n, m;
static int ans = 0;
static int[][] grid;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
grid = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
grid[i][j] = sc.nextInt();
}
}
bfs(0, 0);
System.out.println(ans);
}
public static void bfs(int x, int y) {
int[][] delta = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
boolean[][] visited = new boolean[n][m];
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[] {x, y});
visited[x][y] = true;
while(!q.isEmpty()) {
int[] node = q.poll();
x = node[0];
y = node[1];
if (x == n - 1 && y == m - 1) {
ans = 1;
return;
}
for(int i = 0; i < 4; i++) {
int nx = x + delta[i][0];
int ny = y + delta[i][1];
if (inRange(nx, ny) && !visited[nx][ny]) {
if (grid[nx][ny] == 0) continue;
visited[nx][ny] = true;
q.offer(new int[] {nx, ny});
}
}
}
}
public static boolean inRange(int x, int y) {
if (0 <= x && x < n && 0 <= y && y < m) return true;
return false;
}
}
갈 수 있는 곳들
import java.util.*;
import java.io.*;
class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
static int n, k;
static int ans = 0;
static int[][] grid;
static boolean[][] visited;
static Queue<Pair> q = new ArrayDeque<>();
public static void main(String[] args) throws IOException {
init();
bfs();
System.out.println(ans);
}
public static void bfs() {
int[][] delta = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!q.isEmpty()) {
Pair pair = q.poll();
int x = pair.x;
int y = pair.y;
for (int i = 0; i < 4; i++) {
int nx = x + delta[i][0];
int ny = y + delta[i][1];
if (inRange(nx, ny) && !visited[nx][ny]) {
if (grid[nx][ny] == 1) continue;
visited[nx][ny] = true;
q.offer(new Pair(nx, ny));
ans++;
}
}
}
}
public static boolean inRange(int x, int y) {
return 0 <= x && x < n && 0 <= y && y < n;
}
public static void init() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
grid = new int[n][n];
visited = new boolean[n][n];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++) {
grid[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < k; i++) {
st = new StringTokenizer(br.readLine());
int tempx = Integer.parseInt(st.nextToken()) - 1;
int tempy = Integer.parseInt(st.nextToken()) - 1;
q.offer(new Pair(tempx, tempy));
visited[tempx][tempy] = true;
ans++;
}
}
}
'알고리즘' 카테고리의 다른 글
[코드트리] 2024/08/22 - K번 최댓값으로 이동하기 (0) | 2024.08.22 |
---|---|
[코드트리 조별과제] 2024/08/12 - 수들 중 최솟값 최대화하기 (0) | 2024.08.12 |
[코드트리] 2024/08/11 - 최소 점프 횟수, n개의 점 중 m개 고르기 (0) | 2024.08.11 |