작성
·
56
0
안녕하세요 혹시 이 문제를 풀 때 꼭 dist배열을 만들어야 될까요? 제 코드를 아래 보여드립니다.
바로 L를 반환하게 만들었는데 이래도 괜찮을지요?
package org.youyk.inflearn.latest.sec07.Problem4;
import java.util.*;
class Solution1 {
static int[] dx = {0,0,-1,1};
static int[] dy = {1,-1,0,0};
public int solution(int[][] board){
int answer = 0;
int[][] ch = new int[board.length][board[0].length];
Queue<int[]> queue =new LinkedList<>();
int n = board.length;
int m = board[0].length;
queue.add(new int[]{0,0});
ch[0][0] = 1;
int L=0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
int[] poll = queue.poll();
if(poll[0] == n-1 && poll[1] == m-1){
return L;
}
for(int j=0;j<4;j++){
int xx = dx[j] + poll[0];
int yy = dy[j] + poll[1];
if(xx>=0 && yy>=0 && xx<n && yy<m && board[xx][yy] ==0){
board[xx][yy] = 1;
queue.add(new int[]{xx,yy});
}
}
}
L++;
}
return -1;
}
public static void main(String[] args){
Solution1 T = new Solution1();
int[][] arr={{0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0},
{1, 1, 0, 1, 0, 1, 1},
{1, 1, 0, 1, 0, 0, 0},
{1, 0, 0, 0, 1, 0, 0},
{1, 0, 1, 0, 0, 0, 0}};
int[][] arr3={{0, 0, 1, 1, 1, 1, 1},
{0, 0, 1, 0, 0, 0, 0},
{1, 0, 1, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 1, 0},
{0, 0, 1, 1, 1, 0, 0}};
int[][] arr2={{1, 0, 0, 0, 1, 0, 0},
{0, 1, 1, 1, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0},
{1, 1, 0, 1, 1, 1, 1},
{1, 1, 0, 1, 0, 0, 0},
{1, 0, 0, 0, 1, 0, 0},
{1, 0, 1, 0, 1, 0, 0}};
System.out.println(T.solution(arr));
System.out.println(T.solution(arr2));
System.out.println(T.solution(arr3));
}
}