728x90
https://programmers.co.kr/learn/courses/30/lessons/1844
코딩테스트 연습 - 게임 맵 최단거리
[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1
programmers.co.kr
음 완전 bfs~
import java.util.*;
class Solution {
static int[] row = {0,0,1,-1};
static int[] col = {1,-1,0,0};
//bfs
public int solution(int[][] maps) {
int answer = -1;
int N = maps.length;
int M = maps[0].length;
boolean[][] visited = new boolean[N][M];
Queue<node> q = new LinkedList<>();
q.offer(new node(N-1, M-1));
visited[N-1][M-1] = true;
int nx, ny;
while(!q.isEmpty()) {
node nd = q.poll();
if(nd.x == 0 && nd.y==0) {
return maps[nd.x][nd.y];
}
for(int i=0;i<4;i++) {
nx = nd.x + row[i];
ny = nd.y + col[i];
if(nx<0 || nx>=N || ny<0 || ny>=M || visited[nx][ny]) continue;
if(maps[nx][ny]==1) {
q.offer(new node(nx, ny));
visited[nx][ny] = true;
maps[nx][ny] = maps[nd.x][nd.y] + 1;
}
}
}
return answer;
}
static class node{
int x, y;
node(int x, int y){
this.x=x;
this.y=y;
}
}
}
728x90
'공부 > Algorithms w.Java' 카테고리의 다른 글
[Java] 백준 9934 - 완전 이진 트리 (0) | 2022.11.10 |
---|---|
백준 2098 - 외판원 순회; Java (0) | 2022.04.11 |
프로그래머스-숫자 게임; Java (1) | 2022.02.20 |
프로그래머스-가장 큰 수; Java (0) | 2022.02.20 |
프로그래머스-기지국 설치; Java (0) | 2022.02.19 |