백준 자바 입력 받기
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenzier;
//StringTokenizer StringTokenizer는 문자열을 구분자(토큰)로 나누는 데 사용됩니다. 기본 구분자는 공백입니다.
//주로 공백이나 다른 구분자로 구분된 문자열을 쉽게 분리하기 위해 사용합니다.
//주요 메소드:
//nextToken(): 다음 토큰을 반환합니다.
//hasMoreTokens(): 더 많은 토큰이 있는지 여부를 반환합니다.
//BufferedReader
// readLine(): 한 줄을 읽고, 그 줄을 문자열로 반환합
// 그러므로 BufferedReader를 사용할 경우 반드시 타입 변환을 해줘야됨.
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine);
int n = Integer.parseInt(br.readLine());
for (int i = 0; 1 < n; i++) {
StringTokenizer st = new StringTokenizer (br.readLine));
int s = Integer.parseInt(st.nextToken);
for (int j= 0; j< s; j++) {
int data = Integer.parseInt(st.nextToken);
sb.append(data).append('\n');
}
}
System.out.println(sb);
br.close();
import java.util.*;
public class Main {
public static boolean[] visited = new boolean[9];
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
// DFS 함수 정의
public static void dfs(int x) {
// 현재 노드를 방문 처리
visited[x] = true;
System.out.print(x + " ");
// 현재 노드와 연결된 다른 노드를 재귀적으로 방문
for (int i = 0; i < graph.get(x).size(); i++) {
int y = graph.get(x).get(i);
if (!visited[y]) dfs(y);
}
}
// BFS 함수 정의
public static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
q.offer(start);
// 현재 노드를 방문 처리
visited[start] = true;
// 큐가 빌 때까지 반복
while(!q.isEmpty()) {
// 큐에서 하나의 원소를 뽑아 출력
int x = q.poll();
System.out.print(x + " ");
// 해당 원소와 연결된, 아직 방문하지 않은 원소들을 큐에 삽입
for(int i = 0; i < graph.get(x).size(); i++) {
int y = graph.get(x).get(i);
if(!visited[y]) {
q.offer(y);
visited[y] = true;
}
}
}
}
public static void main(String[] args) {
// 그래프 초기화
for (int i = 0; i < 9; i++) {
graph.add(new ArrayList<Integer>());
}
// 노드 1에 연결된 노드 정보 저장
graph.get(1).add(2);
graph.get(1).add(3);
graph.get(1).add(8);
// 노드 2에 연결된 노드 정보 저장
graph.get(2).add(1);
graph.get(2).add(7);
// 노드 3에 연결된 노드 정보 저장
graph.get(3).add(1);
graph.get(3).add(4);
graph.get(3).add(5);
// 노드 4에 연결된 노드 정보 저장
graph.get(4).add(3);
graph.get(4).add(5);
// 노드 5에 연결된 노드 정보 저장
graph.get(5).add(3);
graph.get(5).add(4);
// 노드 6에 연결된 노드 정보 저장
graph.get(6).add(7);
// 노드 7에 연결된 노드 정보 저장
graph.get(7).add(2);
graph.get(7).add(6);
graph.get(7).add(8);
// 노드 8에 연결된 노드 정보 저장
graph.get(8).add(1);
graph.get(8).add(7);
dfs(1);
}
백준 1260번 문제
import java.util.*;
import java.io.*;
public class Main {
StringBuilder sb = new StringBuilder();
static boolean[] visited;
static Queue<Integer> q ;
static ArrayList<Integer>[] graph;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 첫 번째 줄 읽기
StringTokenizer st = new StringTokenizer(br.readLine());
int numVertices = Integer.parseInt(st.nextToken());
int numEdges = Integer.parseInt(st.nextToken());
int startVertex = Integer.parseInt(st.nextToken());
graph = new ArrayList[numVertices + 1];
for (int i = 0; i < numVertices+1; i++) {
graph[i] = new ArrayList<Integer>();
}
// 간선 정보 저장
for (int j = 0; j < numEdges; j++) {
st = new StringTokenizer(br.readLine());
int node1 = Integer.parseInt(st.nextToken());
int node2 = Integer.parseInt(st.nextToken());
graph[node1].add(node2);
graph[node2].add(node1);
}
// node가 1부터 시작하기 때문에 N + 1
visited = new boolean[numVertices+1];
dfs(startVertex);
System.out.println();
visited = new boolean[numVertices+1];
bfs(startVertex);
// BufferedReader 닫기 (권장)
br.close();
}
public static void dfs(int x){
visited[x] = true;
System.out.print(x +" ");
//sb.append(x+" ");
Collections.sort(graph[x]); // 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문
for(int i=0;i<graph[x].size();i++){
int y = graph[x].get(i);
if (!visited[y]) {
dfs(y);
}
}
}
public static void bfs(int x){
q=new LinkedList<Integer>();
q.offer(x);
visited[x]=true;
while(!q.isEmpty()){
int temp = q.poll();
System.out.print(temp+" ");
// sb.append(temp+" ");
Collections.sort(graph[temp]); // 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문
for(int i=0;i<graph[temp].size();i++){
int y = graph[temp].get(i);
if (!visited[y]) {
q.offer(y);
visited[y] = true;
}
}
}
}
}
백준 2178번
import java.util.*;
import java.io.*;
import java.awt.Point;
public class Main{
static StringBuilder sb = new StringBuilder();
static Queue<Point> q ;
static ArrayList<Integer>[] graph;
// 동서남북
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static int[][] arr;
static boolean[][] visited;
static int rows,cols;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
rows = Integer.parseInt(st.nextToken());
cols =Integer.parseInt(st.nextToken());
arr = new int[rows][cols];
visited = new boolean[rows][cols];
for(int i=0;i<rows;i++){
String line = br.readLine();
for(int j=0;j<cols;j++){
arr[i][j] = line.charAt(j) - '0';
}
}
bfs(0,0);
System.out.println(arr[rows-1][cols-1]);
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
//arr[i][j] = line.charAt(j) - '0';
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
static void bfs(int x,int y){
q= new LinkedList<>();
q.offer(new Point(x,y));
visited[x][y] =true;
while(!q.isEmpty()){
Point currentPoint = q.poll();
for(int i=0;i<4;i++){
int nextX = currentPoint.x +dx[i];
int nextY = currentPoint.y +dy[i];
//1. 범위 내에 있는가?
if(nextX <0 || nextX>=rows || nextY <0 || nextY>=cols)
continue;
//2.막힌 길인가?
if (arr[nextX][nextY]==0)
continue;
//3.이미 방문했나?
if(visited[nextX][nextY])
continue; // 방문했으면(true 이면) 제끼기
// 모든 조건에 해당되지 않음. 즉, 갈 수 있는 길이면
// queue에 삽입해주고 방문처리.
q.offer(new Point(nextX,nextY));
visited[nextX][nextY]=true;
// 그리고 최소 칸의 수를 구해야되므로 칸에 1씩 누적해서
// 도착 칸이면 그 값이 지냐아 하는 최소 칸의 수.
arr[nextX][nextY] = arr[currentPoint.x][currentPoint.y]+1;
}
}
}
}
백준 1303번
import java.util.*;
import java.io.*;
import java.awt.Point;
public class Main{
static StringBuilder sb = new StringBuilder();
static int n;
static int m;
static String[][] arr;
static boolean[][] visited;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static int count;
static int sumW;
static int W;
static int sumB;
static int B;
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());
arr = new String[m][n];//[세로크기][가로크기]
// 배열은 세로크기에 가로크기임
visited = new boolean[m][n];
for(int i=0;i<m;i++){
String line = br.readLine();
for(int j=0;j<n;j++){
arr[i][j] = line.substring(j,j+1);
}
}
sumW=0;
sumB=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(visited[i][j]){
continue;
}
else{
String nowColor = arr[i][j];
W=0;
B=0;
dfs(i,j,nowColor);
if(nowColor.equals("W")){
sumW+=W*W;
}
else if (nowColor.equals("B")){
sumB+=B*B;
}
}
}
}
System.out.print(sumW+" "+sumB);
}
static void dfs(int x,int y,String nowColor){
visited[x][y] = true;
if(nowColor.equals("W")) W++;
else if(nowColor.equals("B"))B++;
for(int i=0;i<4;i++){
int nextX = x+dx[i];
int nextY = y+dy[i];
if(nextX<0 || nextX>=m || nextY<0 || nextY>=n)
continue;
if (!(arr[nextX][nextY].equals(nowColor)))
continue;
if( visited[nextX][nextY])
continue;
dfs(nextX,nextY,nowColor);
}
}
}
'코딩테스트' 카테고리의 다른 글
[알고리즘 문제 풀이] 백준 13549 숨바꼭질3 (BFS/DFS) (학습용) (0) | 2024.07.06 |
---|---|
[알고리즘 문제 풀이] 백준 12851 (BFS/DFS) (학습용) (0) | 2024.07.05 |
[알고리즘 문제 풀이] 백준 16953번 A->B (BFS/DFS) (학습용) (0) | 2024.07.05 |
[알고리즘 문제 풀이] 백준 2606번 바이러스 (BFS/DFS) (0) | 2024.07.04 |
[알고리즘 문제 풀이] 백준 1743번 음식물 피하기 (BFS/DFS) (0) | 2024.07.04 |