이 영역을 누르면 첫 페이지로 이동
천천히 꾸준히 조용히 블로그의 첫 페이지로 이동

천천히 꾸준히 조용히

페이지 맨 위로 올라가기

천천히 꾸준히 조용히

천천히 꾸준히 조용히.. i3months 블로그

[백준] 25417 고속의 숫자 탐색 - Java

  • 2022.08.07 17:43
  • Algorithm/Baekjoon
반응형

 

 

 

걸어가는 경우와 뛰어가는 경우 두 가지를 모두 고려해야 한다.

 

visit을 boolean타입이 아니라 int로 설정한 후, 초기값을 -1로 초기화하고 최단거리로 가는 경우면 계속해서 갱신해주는 방식으로 풀었다.

 

visit을 boolean으로 설정하는 대신, Locate객체에 cnt변수를 추가하고 먼저 뛰어가게 한 후 걸어가는 경우를 확인하는 방식으로 bfs를 돌려도 해결할 수 있을 것 같다.

 

중간에 cur.r 대신 r으로 바꿔써서 시간낭비가 있었다.

 

 

import java.util.*;
import java.io.*;
import java.math.*;

public class Main {

    static int[][] map = new int[5][5];    
    static int[] dr = {-1,1,0,0};
    static int[] dc = {0,0,-1,1};

    static int destinationR = 0;
    static int destinationC = 0;

    static int[][] visit = new int[5][5];

    static int r, c;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        for(int i=0; i<5; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int j=0; j<5; j++){
                map[i][j] = Integer.parseInt(st.nextToken());
                if(map[i][j] == 1){
                    destinationR = i;
                    destinationC = j;
                }
                visit[i][j] = -1;
            }
        }

        StringTokenizer st = new StringTokenizer(br.readLine());

        r = Integer.parseInt(st.nextToken());
        c = Integer.parseInt(st.nextToken());        

        Queue<Locate> q = new LinkedList<>();

        q.add(new Locate(r,c));

        int ans = Integer.MAX_VALUE;
     
        visit[r][c] = 0;
        
        while(!q.isEmpty()){
            Locate cur = q.poll();         
            
            if(cur.r == destinationR && cur.c == destinationC){
                ans = Math.min(ans, visit[cur.r][cur.c]);
            }

            for(int i=0; i<4; i++){ // 먼저 뛰어가게 해야됨    
                int nextR = cur.r;
                int nextC = cur.c;   

                while(true){
                    nextR += dr[i];
                    nextC += dc[i];
                    
                    if(nextR >= 5 || nextR <= -1 || nextC >= 5 || nextC <= -1){
                        nextR -= dr[i];
                        nextC -= dc[i];
                        break;
                    } 
                    
                    if(map[nextR][nextC] == -1){
                        nextR -= dr[i];
                        nextC -= dc[i];
                        break;
                    }

                    if(map[nextR][nextC] == 7){
                        break;
                    }
                }

                if(r == nextR && c == nextC){
                    continue;
                }

                if(visit[nextR][nextC] == -1){
                    visit[nextR][nextC] = visit[cur.r][cur.c] + 1;
                    q.add(new Locate(nextR, nextC));
                }else{
                    if(visit[nextR][nextC] > visit[cur.r][cur.c] + 1){
                        visit[nextR][nextC] = visit[cur.r][cur.c] + 1;
                        q.add(new Locate(nextR, nextC));
                    }
                }
                
            }

            for(int i=0; i<4; i++){
                int nextR = cur.r + dr[i];
                int nextC = cur.c + dc[i];

                if(nextR >= 5 || nextR <= -1 || nextC >= 5 || nextC <= -1){
                    continue;
                }  

                if(map[nextR][nextC] == -1){
                    continue;
                }

                if(visit[nextR][nextC] == -1){
                    visit[nextR][nextC] = visit[cur.r][cur.c] + 1;
                    q.add(new Locate(nextR, nextC));
                }else{
                    if(visit[nextR][nextC] > visit[cur.r][cur.c] + 1){
                        visit[nextR][nextC] = visit[cur.r][cur.c] + 1;
                        q.add(new Locate(nextR, nextC));
                    }
                }
            }

        }     

        System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);
        
    }
}

class Locate{
    int r,c;
    int cnt = 0;
    Locate(int r, int c){
        this.r = r;
        this.c = c;        
    }
}
반응형

'Algorithm > Baekjoon' 카테고리의 다른 글

[백준] 1600 말이 되고픈 원숭이 - Java  (0) 2022.08.13
[백준] 16235 나무 재테크 - Java  (0) 2022.08.13
[백준] 16652 Binary tree - Java  (0) 2022.08.06
[백준] 16652 Email Destruction - Java  (0) 2022.08.06
[백준] 10895 Great Pow! - Java  (0) 2022.08.05

댓글

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 라인

    라인

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • [백준] 1600 말이 되고픈 원숭이 - Java

    [백준] 1600 말이 되고픈 원숭이 - Java

    2022.08.13
  • [백준] 16235 나무 재테크 - Java

    [백준] 16235 나무 재테크 - Java

    2022.08.13
  • [백준] 16652 Binary tree - Java

    [백준] 16652 Binary tree - Java

    2022.08.06
  • [백준] 16652 Email Destruction - Java

    [백준] 16652 Email Destruction - Java

    2022.08.06
다른 글 더 둘러보기

정보

천천히 꾸준히 조용히 블로그의 첫 페이지로 이동

천천히 꾸준히 조용히

  • 천천히 꾸준히 조용히의 첫 페이지로 이동

검색

방문자

  • 전체 방문자
  • 오늘
  • 어제

카테고리

  • 분류 전체보기 (677)
    • Algorithm (205)
      • Data Structure (5)
      • Theory && Tip (33)
      • Baekjoon (166)
      • ALGOSPOT (1)
    • Spring (123)
      • Spring (28)
      • Spring Web MVC (20)
      • Spring Database (14)
      • Spring Boot (6)
      • Spring 3.1 (11)
      • Spring Batch (6)
      • Spring Security (16)
      • JPA (12)
      • Spring Data JPA (5)
      • QueryDSL (4)
      • eGovFramework (1)
    • Programming Language (74)
      • C (25)
      • C++ (12)
      • Java (19)
      • JavaScript (15)
      • Python (1)
      • PHP (2)
    • Computer Science (142)
      • Machine Learning (38)
      • Operating System (18)
      • Computer Network (28)
      • System Programming (22)
      • Universial Programming Lang.. (8)
      • Computer Architecture (4)
      • Compiler Design (11)
      • Computer Security (13)
    • Database (21)
      • Database (7)
      • MySQL (3)
      • Oracle (3)
      • Redis (5)
      • Elasticsearch (3)
    • DevOps (20)
      • Docker && Kubernetes (8)
      • Jenkins (4)
      • Amazon Web Service (8)
    • Mobile (28)
      • Android (21)
      • Flutter (7)
    • 💡 솔루션 (17)
    • 👥 모각코 (9)
    • 💬 기록 (7)
    • 📚 공부 (6)
    • -------------- (25)

최근 글

나의 외부 링크

메뉴

  • 홈
반응형

정보

i3months의 천천히 꾸준히 조용히

천천히 꾸준히 조용히

i3months

블로그 구독하기

  • 구독하기
  • RSS 피드

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. Copyright © i3months.

티스토리툴바