Maze_DFS
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.


์ด ๋ฌธ์ ์ ์ค์ํ ํน์ง์ด์ ํต์ฌ์, ๋ฒฝ('1')์ ๋ง๋๊ธฐ ์ ๊น์ง ์ญ ์งํํ๋ ๊ฒ์ด๋ค!
DFS ํ์ด ๋ฐฉ๋ฒ์ ํน์ง
ํจ์ ํธ์ถ ์ ํ๋ฒ ํธ์ถํ๋ฉด ๊น์ด ์๊ฒ ๋๊น์ง ํ๊ณ ๋ ๋ค.
์๋ฃ๊ตฌ์กฐ : -
์๊ณ ๋ฆฌ์ฆ 1. start(x,y)์์ ์/ํ/์ข/์ฐ๋ก ํ์ํ๋ค. 2. ์/ํ/์ข/์ฐ ๋ฐฉํฅ์ผ๋ก ๋ฒ์๊ฐ ์ ํจํ ๋ฒ์๋์ ์ญ ๊ทธ ๋ฐฉํฅ์ผ๋ก ๊ณ์ ์งํํ๋ค. x += dir[0], y += dir[1]
์๊ณ ๋ฆฌ์ฆ์ Java๋ก ๊ตฌํ
package graph;
public class Maze_DFS_practice {
public static void main(String[] args) {
int[][] maze ={
{0,0,1,0,0},
{0,0,0,0,0},
{0,0,0,1,0},
{1,1,0,1,1},
{0,0,0,0,0}
};
int[] start = {0,4};
int[] dest = {4,4};
int[] dest2 = {3,2};
Maze_DFS_practice a = new Maze_DFS_practice();
System.out.println("Start(0,4) and Destination(4,4) : "+a.hasPath(maze,start,dest));
System.out.println("Start(0,4) and Destination(3,2) : "+a.hasPath(maze,start,dest2));
}
int m,n;
int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
public boolean hasPath(int[][] maze, int[] start, int[] dest) {
//์์ธ ์ ์ธ
if(maze == null || maze.length == 0) return false;
m = maze.length;
n = maze[0].length;
//๊ทธ๋ฆ ์์ฑ
boolean[][] visited = new boolean[m][n];//์ค๋ณต ๋ฐฉ์ง๋ฅผ ์ํด mazeํฌ๊ธฐ์ boolen ๋ฐฐ์ด์ ์์ฑํ๋ค. ex ) {0,1} = true, {2,4} = true ๋ฅผ ์ ์ฅ.
return dfs(maze,start,dest,visited);
}
public boolean dfs(int[][] maze, int[] start, int[] dest, boolean[][] visited) {
if(start[0] < 0 || start[0] >= m || start[1] < 0 || start[1] >= n || visited[start[0]][start[1]])
return false;
//maze ์ ํจ ๋ฒ์๋ด์ ์ํ๋ค๋ฉด
visited[start[0]][start[1]] = true;
if(start[0] == dest[0] && start[1] == start[1])
return true;
//4๋ฐฉ์ผ๋ก ํ์.
for(int[] dir:dirs) {
int x = start[0];
int y = start[1];
//THE CORE PART OF THIS PROBLEM. KEEP ROLLING TILL HIT BY WALL('1')
while(x>=0 && x<m && y>=0 && y<n && maze[x][y] != 1) {
x += dir[0];
y += dir[1];
}
x -= dir[0];
y -= dir[1];
if(dfs(maze,new int[] {x,y}, dest, visited)) {
return true;
}
}
return false;
}
}
Last updated
Was this helpful?