๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 2665_๋ฏธ๋กœ๋งŒ๋“ค๊ธฐ

๋ฟŒ์•ผ._. 2023. 5. 23. 22:33

Gold IV

๋ฌธ์ œ(์ถœ์ฒ˜: 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

์ƒ๊ฐ๐Ÿค”