백준 2210번 숫자판 점프(JAVA)

민성재·2021년 4월 17일
1

Algorithm & Coding Test

목록 보기
2/20

  • 풀이 방식
    먼저 5*5 배열을 담는 map[][]
    6자리 숫자를 담는 배열 arr[]
    6자리 숫자를 스트링으로 변환해서 중복없이 담는 list 를 선언

map의 모든 지점에서 동서남북으로 dfs를 모두 호출(단, 배열 범위 안일때만)

핵심은 dfs를 전부 호출해서 만든 6자리 숫자를 스트링으로 바꾼뒤 리스트에 넣을때

indexOf() 는 어레이리스트에 인자가 있으면 인덱스값을, 없으면 -1을 리턴하기 때문에 위의 코드는 리스트에 str이 없을때만 리스트에 추가하겠다는 의미 (중복을 제거할 수 있다)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;


public class Main {
	public static int [][] map;
	public static int[] dx = { -1, 1, 0, 0 };
    public static int[] dy = { 0, 0, -1, 1 };
    public static int [] arr ;
    public static ArrayList<String> list;
	public static void main(String[] args ) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		Scanner sc = new Scanner(System.in);
		
		map = new int [5][5]; //맵 상태
		arr= new int [6]; //6자리 정답담는 배열
		//맵 세팅
		for (int i = 0; i < 5; i++) {
            st=new StringTokenizer(br.readLine());
            for (int j = 0; j < 5; j++) {
                map[i][j] = Integer.parseInt(st.nextToken());
            }
        }
		
		list = new ArrayList<>();
		for(int i = 0 ; i < 5 ; i++) 
			for(int j = 0 ; j < 5 ; j++) 
				dfs(i,j,1);
			
		
		System.out.println(list.size());
	}
	
	public static void dfs(int x, int y , int depth) {
		//탈출조건
		if(depth > 6) {
			//정답 배열에 있는 정수 뽑아서 스트링으로 변환
			String str = "";
			for(int i = 0 ; i<arr.length; i++) 
				str+= Integer.toString(arr[i]);
			
			
			//리스트에 없다면 넣음(중복 제거)
			if(list.indexOf(str) < 0)
				list.add(str);
			
			return;
		}
		
		
		//depth 6될때까진 배열 채움
		arr[depth-1] = map[x][y];
		
		//동서남북 변수
		for(int i = 0 ; i < 4 ; i ++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			
			//동서남북 범위 벗어나지않으면 전부 dfs호출
			if(nx>=0 && nx<5 && ny>=0 && ny<5) 
				dfs(nx,ny,depth+1);
			
		}
	}
}
profile
민성재 개발 블로그

0개의 댓글