다익스트라 알고리즘, bfs
import java.util.*;
import java.io.*;
public class Main{
static StringBuilder sb=new StringBuilder();
static int map[][];
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
int m=Integer.parseInt(st.nextToken());
map=new int[m][n];
for(int i=0;i<m;i++) {
String line=br.readLine();
for(int j=0;j<n;j++) {
map[i][j]=line.charAt(j)-'0';
}
}
bfs();
}
public static void bfs() {
int dist[][]=new int[map.length][map[0].length];
for(int i=0;i<dist.length;i++)
Arrays.fill(dist[i],Integer.MAX_VALUE);
Queue<Integer[]> queue=new LinkedList<>();
int dy[]= {0,0,-1,1};
int dx[]= {-1,1,0,0};
queue.add(new Integer[] {0,0,0});
dist[0][0]=0;
while(!queue.isEmpty()) {
Integer temp[]=queue.poll();
int nowY=temp[0];
int nowX=temp[1];
int broken=temp[2];
// System.out.println(123);
for(int i=0;i<4;i++) {
int nextY=nowY+dy[i];
int nextX=nowX+dx[i];
if(nextY<0||nextX<0||nextY>=map.length||nextX>=map[0].length)
continue;
if(map[nextY][nextX]==0) {
if(dist[nextY][nextX]>broken) {
dist[nextY][nextX]=broken;
queue.add(new Integer[] {nextY,nextX,broken});
}
}
else {
if(dist[nextY][nextX]>broken+1) {
dist[nextY][nextX]=broken+1;
queue.add(new Integer[] {nextY,nextX,broken+1});
}
}
}
}
System.out.println(dist[map.length-1][map[0].length-1]);
}
}
다익스트라 알고리즘의 개념을 1번 더 상기한 문제다.
하루에 백준 1문제 이상 푸는 것을 목표로 하고있다.
https://solved.ac/profile/anwlro0212