๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/2665)
< ๋ฏธ๋ก ๋ง๋ค๊ธฐ>
๋ฌธ์ ํ์ด
bfs๋ฅผ ํ์ฉํ์ฌ ๋ชจ๋ ๋ฐฉ์ ํ์ํ๋ค. ํฐ ๋ฐฉ์ด๋ฉด ๋ฐ๊พธ์ด์ผ ํ ์ต์์ ์๋ฅผ ์ ๊ฐ์ผ๋ก ๊ทธ๋๋ก ์ ์งํ๊ณ ๊ฒ์ ๋ฐฉ์ธ ๊ฒฝ์ฐ์๋ ๋ฐ๊พธ์ด์ผ ํ ์ต์์ ์๋ฅผ ์ ๊ฐ +1๋ก ๋ฐ๊ฟ์ค๋ค. ์ด๋ ์ต์์ ์๋ฅผ ๊ตฌํ๊ธฐ ์ํด ์กฐ๊ฑด์ ์ ์ค์ ํ๋ค.
- my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class _2665_ { // ๋ฏธ๋ก๋ง๋ค๊ธฐ
static boolean arr[][];
static int result[][], n;
static int dx[]= {-1,1,0,0};
static int dy[]= {0,0,-1,1};
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(bf.readLine());
arr=new boolean[n][n];
result=new int[n][n];
for(int i=0; i<n; i++) {
String s=bf.readLine();
for(int j=0; j<n; j++) {
if(s.charAt(j)=='0') arr[i][j]=false; // ๊ฒ์ ๋ฐฉ
else arr[i][j]=true; // ํฐ ๋ฐฉ
result[i][j]=-1;
}
}
search(0,0);
System.out.println(result[n-1][n-1]);
}
private static void search(int i, int j) {
Queue<int[]>queue=new LinkedList<>();
queue.add(new int[] {i,j});
result[i][j]=0;
while(!queue.isEmpty()) {
int temp[]=queue.poll();
for(int k=0; k<4; k++) {
int x=temp[0]+dx[k];
int y=temp[1]+dy[k];
if(x>=0 && x<n && y>=0 && y<n) {
if(arr[x][y]) { // ํฐ ๋ฐฉ
if(result[x][y]==-1 || result[x][y]>result[temp[0]][temp[1]]) {
result[x][y]=result[temp[0]][temp[1]];
queue.add(new int[] {x,y});
}
}else { // ๊ฒ์ ๋ฐฉ
if(result[x][y]==-1 || result[x][y]>result[temp[0]][temp[1]]+1) {
result[x][y]=result[temp[0]][temp[1]]+1;
queue.add(new int[] {x,y});
}
}
}
}
}
}
}
- Main
- n ์ ๋ ฅ
- arr : ์์ด ์ ๋ ฅ
- result: ๋ฐ๊พธ์ด์ผ ํ ์ต์์ ๊ฒ์ ๋ฐฉ์ ์
- search ํจ์ ํธ์ถ ํ result [n-1][n-1] ์ถ๋ ฅ
- search
- queue์ ์์ ์์น์ธ (0,0) ๋ฃ๊ณ result๋ฅผ 0์ผ๋ก ์ ์ฅ
- queue๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณต -> ์ํ์ข์ฐ ํ์ -> ํฐ ๋ฐฉ์ผ ๋ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๊ฑฐ๋ ๋ฐ๊พธ์ด์ผ ํ ๊ฒ์ ๋ฐฉ์ ์๊ฐ ์ต์๋ผ๋ฉด update/ ๊ฒ์ ๋ฐฉ์ผ ๋ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๊ฑฐ๋ ๋ฐ๊พธ์ด์ผ ํ ๊ฒ์ ๋ฐฉ์ ์๊ฐ ์ต์๋ผ๋ฉด update
์๊ฐ๐ค

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Baekjoon] 1937_์์ฌ์์ด ํ๋ค (2) | 2023.05.25 |
|---|---|
| [Baekjoon] 16954_์์ง์ด๋ ๋ฏธ๋ก ํ์ถ (0) | 2023.05.24 |
| [Baekjoon] 27211_๋๋ ํ์ฑ (0) | 2023.05.21 |
| [Baekjoon] 1261_์๊ณ ์คํ (1) | 2023.05.12 |
| [Baekjoon] 16469_์๋ ์ ํ (0) | 2023.04.25 |