자바로 백준 2178 풀기

hong030·2023년 7월 19일
0
  • 실버 1단계 문제

풀이)
시작에서 목표까지 가는 데에 최단 경로를 구해야 하니 BFS로 푼다. 서로 인접한 1칸을 노드로 생각하면 된다.
예를 들어 (1,1)은 (2,1)과 연결되어있고, (4,1)은 (3,1)과 (4,2)와 연결되어있다.

내 코드)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
	
	static int[][] map;
	static int n;
	static int m;
	static boolean[][] visited;
	static int[] dx = { -1, 1, 0, 0 }; //x방향배열-상하
    	static int[] dy = { 0, 0, -1, 1 }; //y방향배열-좌우

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());
		
		map = new int[n][m];
		for(int i=0; i<n; i++) {
			String s = br.readLine();
			for(int j=0; j<m; j++) {
				map[i][j] = s.charAt(j) - '0';
			}
		}
		
		visited = new boolean[n][m];
		visited[0][0] = true;
		bfs(0, 0);
		System.out.println(map[n-1][m-1]);
	}

	public static void bfs(int x, int y) {
		Queue<int[]> q = new LinkedList<>();
		q.add(new int[] {x,y});
		
		while(!q.isEmpty()) {
			int now[] = q.poll();
			int nowX = now[0];
			int nowY = now[1];
			
			for(int i=0; i<4; i++) {
				int nextX = nowX + dx[i];
				int nextY = nowY + dy[i];
				
		                if (nextX < 0 || nextY < 0 || nextX >= n || nextY >= m)
                		    continue;
        		        if (visited[nextX][nextY] || map[nextX][nextY] == 0)
                    		continue;
                    
		                q.add(new int[] {nextX, nextY});
        		        map[nextX][nextY] = map[nowX][nowY] + 1;
                		visited[nextX][nextY] = true;
			}
		}
	}
}
profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글