[Algorithm] (이코테) 미로 탈출 - 파이썬
교재 : 이것이 코딩 테스트다 with 파이썬 >CHAPTER 5 DFS/BFS >실전문제 5-4 미로 탈출 152p 미로 탈출 문제 N x M 크기의 직사각형 형태의 미로에 여러 마리의 괴물이 있어 이를 피해 탈출해야 한다. 현재
velog.io
5 6
101010
111111
000001
111111
111111
가로,세로(행과 열 {행거는 가로, 열쇠는 세로})로 기억합니다.
visited[][]를 사용하지 않고, graph 자체의 값에서 visited효과를 낼 수 있기에 그런방식으로 진행합니다.
class Node{ private int x,y; public Node(int x, int y) { this.x=x; this.y=y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } public class Main { public static int n,m; public static int[][] graph; public static int[] dy = {-1,1,0,0}; public static int[] dx = {0,0,-1,1}; public static void simulate() { Queue<Node> q = new LinkedList<>(); q.offer(new Node(0,0)); while(!q.isEmpty()) { Node node = q.poll(); int x = node.getX(); int y = node.getY(); for(int dir=0;dir<4;dir++) { int nx = dx[dir] + x; int ny = dy[dir] + y; if(nx < 0 || nx >=n || ny < 0 || ny >=m) continue; if(graph[nx][ny] == 0) continue; if(graph[nx][ny] == 1) { graph[nx][ny] = graph[x][y] + 1; q.offer(new Node(nx,ny)); } } } System.out.println(graph[n-1][m-1]); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n=sc.nextInt(); m=sc.nextInt(); graph = new int[n+1][m+1]; for(int i=0;i<n;i++) { String str = sc.next(); for(int j=0;j<m;j++) { graph[i][j] = str.charAt(j)-'0'; } } simulate(); System.out.println(graph); } }
'기타 > 이것이코딩테스트다' 카테고리의 다른 글
[이것이 코딩테스트다][구현] 게임개발 - 구현 관련 문제(이론) (0) | 2022.03.05 |
---|---|
[이것이 코딩테스트다][구현] 왕실의 나이트 - 구현 관련 문제(이론) (0) | 2022.03.05 |
[이것이 코딩테스트다][구현] 시각 - 구현 관련 문제(이론) (0) | 2022.01.15 |
[이것이 코딩테스트다][구현] 상하좌우 - 구현 관련 문제(이론) (0) | 2022.01.15 |