반응형
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[] dr = {1,-1,0,0};
static int[] dc = {0,0,-1,1};
static boolean[][] visited;
static int[][] map;
static int N,M;
static int count;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new int[N][M];
visited = new boolean[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
String line = st.nextToken();
for (int j = 0; j < M; j++) {
map[i][j] = line.charAt(j) - '0';
}
}
bfs(0,0);
System.out.println(map[N-1][M-1]);
}
public static void bfs(int i, int j){
//배열로 할수도 있구나..
Queue<int[]> q = new LinkedList<>();
q.offer(new int[] {i,j}); //가로,세로
while(!q.isEmpty()){
int location[] = q.poll();
visited[i][j] = true;
for(int dir = 0; dir<4; dir++){
int r = location[0] + dr[dir];
int c = location[1] + dc[dir];
if(r >= 0 && c >= 0 && r < N && c < M){
if(map[r][c] != 0 && !visited[r][c]){
q.offer(new int[] {r,c});
visited[r][c] = true;
//map[r][c]에 거쳐온 정점 수가 저장되게...map[n-1][m-1]하면 최단거리
map[r][c] = map[location[0]][location[1]] + 1;
}
}
}
}
}
}
큐에 배열로 저장 가능
dfs로 풀면 안됨
count++로 하지말고 map[a][b]에 거쳐온 노드 수를 쌓는다는 느낌으로,,
반응형
'개발 관련 공부 > 알고리즘' 카테고리의 다른 글
백준 10816 숫자카드2 (0) | 2021.08.18 |
---|---|
백준 1920 수찾기 (0) | 2021.08.17 |
백준 11724 연결 요소의 개수 (0) | 2021.08.13 |
백준 1012 유기농배추 (0) | 2021.08.12 |
백준 2667 (0) | 2021.08.11 |
댓글