반응형
public class boj2178 {
static int N;
static int M;
static int map[][]; // 탐색할 배열
static int visit[][]; // 탐색한 배열 기억
static int dx[] = {1,-1,0,0}; // 동 서
static int dy[] = {0,0,1,-1}; // 남 북
static int Count = 0;
// 동서 남북 탐색후 좌표를 Que에 집어 넣는다.
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];
visit = new int[N][M];
for (int i = 0; i < N; i++) {
String input[] = br.readLine().split(""); //한 행씩 입력 받아서 map에 집어 넣는다
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(input[j]);
}
}
bfs();
System.out.println(Count + 1);
}
// bfs시작
private static void bfs() {
Queue<Node> que = new LinkedList<>();
que.offer(new Node(0,0)); // 0,0 큐에 입력
// 0,0 동 서 남 북 탐색
// que를 뱉으면서 동서남북 탐색후 삽입
while (!que.isEmpty()) {
int size = que.size();
Count++; //탐색이 끝난후 1칸이동
System.out.println("Count : " + Count);
for (int i = 0; i < size; i++) { // poll 메서드쓰면 한번에 다뱉어버리니까 하나씩 꺼내줄라고 for로 돌리자.
Node node = que.poll();
for (int j = 0; j < 4; j++) { // 동서남북 탐색
int sx = node.x + dx[j]; // 동서 sx 는 요기 for문안에서만 유효하니까 node가 기준을 잡고 움직인다.
int sy = node.y + dy[j]; // 남북
// pass 조건 : 1. visit이 0 2. sx,sy 가 0보다 크거나 같고 3. N,M보다 작을떄 4. map[][] == 1일때
System.out.println("sx : " + sx + " sy : " + sy + "||||| Node : [" + node.x + "::" + node.y +"]");
if (sx >= 0 && sy >= 0 && sx < N && sy < M && map[sx][sy] == 1 && visit[sx][sy] == 0) { //if 앞뒤 순서 상관이 있음
//NM <= 아니고 < 인 이유는 배열이니까 0부터 시작
if (sx == (N-1) && sy == (M-1)) {
System.out.println("끝나따");
return;
}
visit[sx][sy] = 1;
que.offer(new Node(sx, sy));
}
}
}
}
}
}
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
https://www.acmicpc.net/problem/2178
BFS 활용 Java 알고리즘 미로탐색 문제
반응형
'기타 > 알고리즘' 카테고리의 다른 글
[알고리즘] 프로그래머스 무인도여행 DFS 풀이 (자바,java) (1) | 2023.04.20 |
---|---|
[알고리즘] 프로그래머스 무인도여행 DFS 풀이 (자바,java) (0) | 2023.04.18 |
[알고리즘] 프로그래머스 - JAVA 미로탈출 (bfs) (0) | 2023.04.17 |
[알고리즘] 프로그래머스 JAVA 리코쳇로봇 - BFS 해결 (0) | 2023.04.15 |
[JAVA 자바] 문자열 역출력, Reverse String (0) | 2021.06.05 |