import java.util.*;
public class Main
{
static final int MAX_N = 10;
static int N, E;
static int[][] Graph = new int[MAX_N][MAX_N];
static void bfs(int node){
boolean[] visited = new boolean[MAX_N];
Queue<Integer> myqueue = new LinkedList<>();
visited[node] = true;
myqueue.add(node);
while (!myqueue.isEmpty()){
int curr = myqueue.remove();
System.out.print(curr + " ");
for(int next = 0; next < N; ++next){
if(!visited[next] && Graph[curr][next] != 0){
visited[next] = true;
myqueue.add(next);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
E = sc.nextInt();
for (int i = 0; i < E; i++){
int u = sc.nextInt();
int v = sc.nextInt();
Graph[u][v] = Graph[v][u] = 1;
}
bfs(0);
}
}
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
import java.util.*;
public class Main
{
static final int MAX_N = 10;
static int[][] D = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static int N;
static int[][] Board = new int[MAX_N][MAX_N];
static class Point {
Point(int r, int c, int d){
row = r; col = c; dist = d;
}
int row, col, dist;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
Board[i][j] = sc.nextInt();
}
}
int sRow, sCol, dRow, dCol;
sRow = sc.nextInt(); sCol = sc.nextInt();
dRow = sc.nextInt(); dCol = sc.nextInt();
System.out.println(bfs(sRow, sCol, dRow, dCol));
}
static int bfs(int sRow, int sCol, int dRow, int dCol){
boolean[][] visited = new boolean[MAX_N][MAX_N];
Queue<Point> myqueue = new LinkedList<>();
visited[sRow][sCol] = true;
myqueue.add(new Point(sRow, sCol, 0));
while(!myqueue.isEmpty()){
Point curr = myqueue.remove();
if(curr.row == dRow && curr.col == dCol){
return curr.dist;
}
for(int i=0; i < 4; i++){
int nr = curr.row + D[i][0], nc = curr.col + D[i][1];
if(nr < 0 || nr > N - 1 || nc < 0 || nc > N - 1) continue;
if(visited[nr][nc]) continue;
if(Board[nr][nc] == 1) continue;
visited[nr][nc] = true;
myqueue.add(new Point(nr, nc, curr.dist + 1));
}
}
return -1;
}
}
https://www.youtube.com/watch?v=yQ7o1Y7X_Rg
감 잡는중
'알고리즘' 카테고리의 다른 글
[백준] 2178번 (java 자바) (0) | 2022.10.05 |
---|---|
DFS 기본 알고리즘 (0) | 2022.09.28 |
[백준] 16236번 (java 자바) (0) | 2022.09.20 |
[백준] 14500번 (java 자바) (0) | 2022.08.24 |
[백준] 9019번 (python 파이썬) (0) | 2022.08.21 |