UnionFind
package basic.graph;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class UnionFind {
static int v, e;
static int[] parent;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
v=Integer.parseInt(st.nextToken());
e=Integer.parseInt(st.nextToken());
parent = new int[v+1];
makeSet();
for (int i = 0; i < e; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
if( findSet(x) == findSet(y) ) {
System.out.println(x + ", " + y + " 사이클 발생!");
System.out.println(Arrays.toString(parent));
return;
}else {
union(x, y);
System.out.println(x + ", " + y + " union!");
System.out.println(Arrays.toString(parent));
}
}
System.out.println("사이클 발생 X");
}
static void makeSet(){
for(int i=1;i<=v;i++){
parent[i] = i;
}
}
static int findSet(int x){
System.out.println(x+"의 부모는 "+parent[x]);
return parent[x]==x ? x : (parent[x]=findSet(parent[x]));
}
static void union(int x, int y){
int px = findSet(x);
int py = findSet(y);
if(px<py) parent[py] = px;
else parent[px] = py;
}
}
DFS, BFS
package basic.dfsbfs;
import java.util.ArrayDeque;
public class DFS_BFS_2DIM {
static int n, m;
static int[][] map = {
{0, 0, 0, 0, 0, 0, 0},
{0, 11, 12, 13, 14, 15, 16},
{0, 21, 22, 23, 24, 25, 26},
{0, 31, 32, 33, 34, 35, 36},
{0, 41, 42, 43, 44, 45, 46},
{0, 51, 52, 53, 54, 55, 56},
{0, 61, 62, 63, 64, 65, 66},
};
static int[] dx = {0,0,-1,1};
static int[] dy = {-1,1,0,0};
static boolean[][] vis;
public static void main(String[] args) throws Exception {
n = map.length;
m = map[0].length;
vis = new boolean[n][m];
bfs(3,3);
}
static void bfs(int x, int y){
ArrayDeque<int[]> q = new ArrayDeque<>();
q.add(new int[]{x,y});
vis[x][y] = true;
while(!q.isEmpty()){
var c = q.poll();
System.out.println(map[c[0]][c[1]]);
for(int d=0;d<4;d++){
int nx = c[0]+dx[d];
int ny = c[1]+dy[d];
if(nx<1 || nx>=n || ny<1 || ny >=m || vis[nx][ny]) continue;
vis[nx][ny] = true;
q.add(new int[]{nx,ny});
}
}
}
static class Node{
int x, y;
Node(int x, int y){
this.x=x; this.y=y;
}
@Override
public String toString(){
return "Node [y="+y+", x="+x+"]";
}
}
static void dfs(int x, int y){
vis[x][y] = true;
System.out.println(map[x][y]);
for(int d=0;d<4;d++){
int nx = x+dx[d];
int ny = y+dy[d];
if(nx<1 || nx >=n || ny<1 || ny>=m || vis[nx][ny]) continue;
dfs(nx, ny);
}
}
}