https://school.programmers.co.kr/learn/courses/30/lessons/1844
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
DFS
public class Solution {
int[] x_list={0,0,1,-1};
int[] y_list={1,-1,0,0};
int[][] visited;
int min_cnt = -1;
public int solution(int[][] maps) {
visited = new int[maps.length][maps[0].length];
int answer = 0;
dfs(0,0, maps, visited, 1);
return min_cnt;
}
public int dfs (int x, int y, int[][] maps, int[][] visited, int cnt){
int height = maps.length;
int width = maps[0].length;
if(x == height-1 && y == width-1){
if (min_cnt== -1){
min_cnt=cnt;
return 0;
}
else if (min_cnt > cnt){
min_cnt=cnt;
return 0;
}
}
int tempx=x;
int tempy=y;
for(int i =0;i<4;i++){
tempx=x+x_list[i];
tempy=y+y_list[i];
if( (tempx>=0 && tempx<height) && (tempy>=0 && tempy<width) ){
if(maps[tempx][tempy] == 1) {
if(visited[tempx][tempy] == 1) continue;
visited[tempx][tempy] = 1;
dfs(tempx, tempy, maps, visited, cnt+1);
visited[tempx][tempy] = 0;
}
}
}
return min_cnt;
}
}
import java.util.*;
class Solution {
Queue<WillVisit> queue = new LinkedList<WillVisit>();
int[][] visited;
int[] xArr = { 0 , 0 , -1, 1};
int[] yArr = {-1, 1, 0, 0};
public int solution(int[][] maps) {
int answer = -1;
int height = maps.length;
int width= maps[0].length;
visited = new int[height][width];
WillVisit wv1 = new WillVisit(0,0,1);
queue.add(wv1);
while(!queue.isEmpty()){
WillVisit wv = new WillVisit(0,0,0);
wv = queue.poll();
if(wv.x == (height-1) && wv.y == (width-1)){
return wv.cnt;
}
for(int i=0; i<4; i++){
int tmpx = wv.x +xArr[i];
int tmpy = wv.y +yArr[i];
if((tmpx >=0 && tmpx < height)
&& (tmpy >=0 && tmpy < width) ) {
if (maps[tmpx][tmpy] == 1 && visited[tmpx][tmpy] ==0 ){
queue.add(new WillVisit(tmpx, tmpy, (wv.cnt)+1));
visited[tmpx][tmpy] = 1;
}
}
}
}
return answer;
}
class WillVisit {
int x;
int y;
int cnt;
public WillVisit(int x, int y, int cnt){
this.x = x;
this.y= y;
this.cnt = cnt;
}
}
}
'Algorithm (Java) > 문제풀이' 카테고리의 다른 글
[자바 / Java] 프로그래머스 - 푸드파이트 대회 (Level1 - 그리디) (0) | 2023.03.07 |
---|---|
[자바/Java] 프로그래머스 -네트워크 (Level3 - BFS) (0) | 2023.03.04 |
[자바/Java] 프로그래머스 - 모의고사 (Level1- 브루트포스) (0) | 2023.03.02 |
[자바/java] 프로그래머스 - 기능개발(Level2 - Queue) (0) | 2023.02.23 |
[자바/java] 프로그래머스 - 같은숫자는 싫어 (Level1 - Stack) (0) | 2023.02.23 |