01-08 08:57
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_63 ๋ฏธ๋กœ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ†ต๋กœ(DFS) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_63 ๋ฏธ๋กœ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ†ต๋กœ(DFS)

miinsun 2022. 3. 3. 19:08

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

7*7 ๊ฒฉ์žํŒ ๋ฏธ๋กœ๋ฅผ ํƒˆ์ถœํ•˜๋Š” ์ตœ๋‹จ๊ฒฝ๋กœ์˜ ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

๊ฒฝ๋กœ์˜ ๊ธธ์ด๋Š” ์ถœ๋ฐœ์ ์—์„œ ๋„์ฐฉ์ ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ์ด๋™ํ•œ ํšŸ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
์ถœ๋ฐœ์ ์€ ๊ฒฉ์ž์˜ (0, 0) ์ขŒํ‘œ์ด๊ณ , ํƒˆ์ถœ ๋„์ฐฉ์ ์€ (6, 6)์ขŒํ‘œ์ด๋‹ค. ๊ฒฉ์žํŒ์˜ 1์€ ๋ฒฝ์ด๊ณ , 0์€ ๋„๋กœ์ด๋‹ค.

๊ฒฉ์žํŒ์˜ ์›€์ง์ž„์€ ์ƒํ•˜์ขŒ์šฐ๋กœ๋งŒ ์›€์ง์ธ๋‹ค.

๋ฏธ๋กœ๊ฐ€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค๋ฉด, ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฒฝ๋กœ๋กœ ์ตœ๋‹จ ๊ฒฝ๋กœ์˜ ๊ธธ์ด๋Š” 12์ด๋‹ค.

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ 7*7 ๊ฒฉ์ž์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 0 0 1 0 0 0
1 1 0 1 0 1 1
1 1 0 1 0 0 0
1 0 0 0 1 0 0
1 0 1 0 0 0 0

์ถœ๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ตœ๋‹จ์œผ๋กœ ์›€์ง์ธ ์นธ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ๋„์ฐฉํ•  ์ˆ˜ ์—†์œผ๋ฉด -1๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

12

 

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	static int[][] board = new int[7][7];
	static int[] dx = {-1, 0, 1, 0};
	static int[] dy = {0, 1, 0, -1};
	static int len = 0;
	static int min = Integer.MAX_VALUE;
	
	public void DFS(int cx, int cy) {
		if(cx == 6 && cy == 6) min = Math.min(min, len);
		else {
			for(int i = 0; i < 4; i++) {
				int nx =  cx + dx[i];
				int ny = cy + dy[i];
				
				//๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ๊ณ„์„  ์ง€์ •
				if(nx >= 0 && nx <= 6 && ny >= 0 && ny <= 6 && board[nx][ny] == 0) {
					board[nx][ny] = 1;
					len++;
					DFS(nx, ny);
					len--;
					board[nx][ny] = 0;
				}
			}
		}
 	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);

		for(int i = 0; i < 7; i++) {
			for(int j = 0; j < 7; j++) {
				board[i][j] = sc.nextInt();
			}
		}
		
		board[0][0] = 1;
		main.DFS(0, 0);
		System.out.println(min);
		sc.close();
		return ;
	}
}
Comments