https://school.programmers.co.kr/learn/courses/30/lessons/1844
나의풀이
import java.util.*;
class Solution {
static int dx[]={-1, 1, 0, 0};
static int dy[]={0, 0, -1, 1};
static int answer = 0;
static boolean[][] visited;
static int xlen, ylen;
public class Node{
int x, y, cost;
Node(int x, int y, int cost){
this.x= x;
this.y= y;
this.cost= cost;
}
}
public int bfs(int[][] maps, Node node){
Queue<Node> q = new LinkedList<>();
Node now =node;
q.offer(node);
visited[now.x][now.y]=true;
while(!q.isEmpty()){
now = q.poll();
int x=now.x;
int y=now.y;
int cost= now.cost;
if((x == xlen-1) && (y == ylen-1)){
return cost;
}
for(int i=0; i<4; i++){
int nextX=x+dx[i];
int nextY=y+dy[i];
if(nextX<0 || nextY<0|| nextX>=xlen || nextY>=ylen){
continue;
}
if(visited[nextX][nextY] == true){
continue;
}
if(maps[nextX][nextY] == 0){
continue;
}
q.offer(new Node(nextX, nextY, cost+1));
visited[nextX][nextY]=true;
}
}
return -1;
}
public int solution(int[][] maps) {
xlen=maps.length;
ylen=maps[0].length;
visited = new boolean[xlen][ylen];
answer=bfs(maps,new Node(0,0,1));
return answer;
}
}
'코테풀이' 카테고리의 다른 글
[프로그래머스] 연속 부분 수열 합의 개수 java (LEVEL2) (0) | 2023.05.11 |
---|---|
[프로그래머스] 네트워크 java (LEVEL3) (0) | 2023.04.30 |
[프로그래머스] 피로도 java (LEVEL2) (0) | 2023.04.30 |
[프로그래머스] 전력망을 둘로 나누기 java (LEVEL2) (0) | 2023.04.30 |
[프로그래머스] 모음사전 java 자바 (LEVEL2) (0) | 2023.04.30 |