https://programmers.co.kr/learn/courses/30/lessons/1844
๊ทธ๋ํ ํ์ ๋ฌธ์ ์ด๋ค. ์์ ์ ํ์๋ ๋ฐฑ์ค ํ ๋งํ ๋ฌธ์ (https://www.acmicpc.net/problem/7576)์ ๋น์ทํ๋ค๊ณ ์๊ฐํด์ Queue๋ฅผ ์ฌ์ฉํ BFS ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ํ์๋ค.
Player ํด๋์ค๋ฅผ ๋ง๋ค์ด ์ขํ ๊ฐ๊ณผ ์ด๋ํ ์นธ ์๋ฅผ ์ ์ฅํ๋๋ก ํ๋ค.
์ฝ๋
import java.util.*;
class Solution {
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
static boolean[][] visited;
static class Player {
int x;
int y;
int count;
public Player(int x, int y, int count) {
this.x = x;
this.y = y;
this.count = count;
}
}
public int solution(int[][] maps) {
visited = new boolean[maps.length][maps[0].length];
int answer = bfs(maps, 0, 0);
return answer;
}
public int bfs(int[][] maps, int a, int b) {
Queue<Player> queue = new LinkedList<Player>();
queue.add(new Player(a, b, 1));
while(!queue.isEmpty()) {
Player player = queue.poll();
visited[player.x][player.y] = true;
if(player.x == maps.length - 1 && player.y == maps[0].length - 1) {
return player.count;
}
for(int i = 0; i < 4; i++) {
int nx = player.x + dx[i];
int ny = player.y + dy[i];
int count = player.count;
if(0 <= nx && nx < maps.length && 0 <= ny && ny < maps[0].length) {
if(maps[nx][ny] == 1 && !visited[nx][ny]) {
queue.add(new Player(nx, ny, count + 1));
visited[nx][ny] = true;
}
}
}
}
return -1;
}
}
๊ฒฐ๊ณผ
์ ํ์ฑ๊ณผ ํจ์จ์ฑ ๋ชจ๋ ํต๊ณผํ๋ค!
'Algorithm > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค - ์์ ๋์งํ (0) | 2022.06.21 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค - ์ผ๊ฐ ๋ฌํฝ์ด (0) | 2022.06.20 |
ํ๋ก๊ทธ๋๋จธ์ค - ๋ ๋งต๊ฒ (0) | 2022.06.05 |
ํ๋ก๊ทธ๋๋จธ์ค - ์์ด ๋๋ง์๊ธฐ (0) | 2022.06.04 |
ํ๋ก๊ทธ๋๋จธ์ค - ๋ฐฐ๋ฌ (0) | 2022.05.09 |