Tag: BFS

0

백준 2178 - 미로탐색

링크https://www.acmicpc.net/problem/2178 문제 풀이기본적인 BFS 문제다. 조건에 맞춰 값을 읽어온 후 탐색을 진행하면 원하는 값을 얻을 수 있다. 전체 소스import java.io.BufferedReader;import java.io.IOError;import java.io.IOException;import java.io.InputStreamReader;import java.util.LinkedList;import java.util.Queue;public class Main { public static int height, width; public static int[] dx = { 0, 0, 1, -1 }; public static int[] dy = { 1, -1, 0, 0 }; public static int[][] map; public static int bfs() { Queue<int[]> q = new LinkedList<>(); boolean check[][] = new boolean[height + 1][width + 1]; q.offer(new int[] { 0, 0 }); check[0][0] = true; int count = 0; while (!q.isEmpty()) { int qSize = q.size(); count++; while (qSize-- > 0) { int[] point = q.remove(); int cntY = point[0]; int cntX = point[1]; if (cntY == height - 1 && cntX == width - 1) { return count; } for (int i = 0; i < 4; i++) { int nY = cntY + dy[i]; int nX = cntX + dx[i]; if (0 <= nY && nY < height && 0 <= nX && nX < width) { if (check[nY][nX] == false && map[nY][nX] == 1) { check[nY][nX] = true; q.offer(new int[] { nY, nX }); } } } } } return count; } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] inputValues = br.readLine().split(" "); height = Integer.parseInt(inputValues[0]); width = Integer.parseInt(inputValues[1]); map = new int[height + 1][width + 1]; for (int h = 0; h < height; h++) { String inputValue = br.readLine(); for (int w = 0; w < width; w++) { // System.out.println(inputValue.charAt(w)); map[h][w] = inputValue.charAt(w) - '0'; } } int count = bfs(); System.out.println(count); br.close(); }}

0

1194-달이차오른다_가자

백준 1194 - 달이 차오른다. 가자https://www.acmicpc.net/problem/1194 문제 해설기존 BFS문제를 푸는 형식에 비트마스킹까지 더해진 문제이다. 비트마스킹을 통해 키를 가지고 있는 각각의 상태들을 체크할 수 있다. 키는 총 6개가 주어지기 때문에 50x50x64 = 160,000 의 공간 복잡도를 갖게 돼 메모리 제한에 걸리지 않는다. 소스 코드#include <bits/stdc++.h>using namespace std;int N, M;char Map[55][55];bool check[1 << 6][55][55];int dx[4] = {1, -1, 0, 0};int dy[4] = {0, 0, 1, -1};queue<pair<int, int>> q;int startY, startX;struct point { int y; int x; int key; int count;};int bfs() { queue<point> q; q.push({startY, startX, 0, 0}); check[0][startY][startX] = true; while (!q.empty()) { int cntY = q.front().y; int cntX = q.front().x; int cntKey = q.front().key; int cntCount = q.front().count; q.pop(); if (Map[cntY][cntX] == '1') { return cntCount; } for (int i = 0; i < 4; i++) { int ny = cntY + dy[i]; int nx = cntX + dx[i]; if (0 >= ny || ny > N || 0 >= nx || nx > M) { continue; } if (check[cntKey][ny][nx] == true) { continue; } if (Map[ny][nx] == '.') { check[cntKey][ny][nx] = true; q.push({ny, nx, cntKey, cntCount + 1}); } else { // 열쇠에 마주쳤을 경우 if ('a' <= Map[ny][nx] && Map[ny][nx] <= 'f') { int key = (1 << (Map[ny][nx] - 'a')); check[cntKey | key][ny][nx] = true; q.push({ny, nx, cntKey | key, cntCount + 1}); } // 문을 만났을 경우 if ('A' <= Map[ny][nx] && Map[ny][nx] <= 'F') { int door = (1 << (Map[ny][nx] - 'A')); if (door & cntKey) { check[cntKey][ny][nx] = true; q.push({ny, nx, cntKey, cntCount + 1}); } } // 출구를 만났을 경우 if (Map[ny][nx] == '1') { q.push({ny, nx, cntKey, cntCount + 1}); } } } } return -1;}void init() { for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { cin >> Map[i][j]; if (Map[i][j] == '0') { startY = i; startX = j; Map[i][j] = '.'; } } }}int main(void) { cin >> N >> M; init(); cout << bfs() << '\n'; return 0;}

0

백준 1726 - 로봇

링크https://www.acmicpc.net/problem/1726 채점 현황 전체 소스 코드#include <iostream>#include <queue>using namespace std;int M, N;int map[101][101];bool check[101][101][4];int dx[4] = {0, 1, -1, 0};int dy[4] = {-1, 0, 0, 1};// char dir[4] = { 'N', 'E', 'W', 'S' };struct point { int y; int x; int dir;};int main(void) { cin >> M >> N; for (int i = 1; i <= M; i++) { for (int j = 1; j <= N; j++) { cin >> map[i][j]; } } point start, goal; int tempY, tempX, tempD; cin >> tempY >> tempX >> tempD; start.y = tempY; start.x = tempX; start.dir = tempD % 4; cin >> tempY >> tempX >> tempD; goal.y = tempY; goal.x = tempX; goal.dir = tempD % 4; queue<point> q; q.push(start); check[start.y][start.x][start.dir] = true; int num = 0; while (!q.empty()) { int q_size = q.size(); while (q_size--) { int y = q.front().y; int x = q.front().x; int d = q.front().dir; q.pop(); if (y == goal.y && x == goal.x && d == goal.dir) { cout << num << '\n'; return 0; } int nextR, nextL; if (d == 0) { nextR = 1; nextL = 2; } else if (d == 1) { nextR = 3; nextL = 0; } else if (d == 2) { nextR = 0; nextL = 3; } else if (d == 3) { nextR = 2; nextL = 1; } if (check[y][x][nextR] == false) { check[y][x][nextR] = true; q.push({y, x, nextR}); } if (check[y][x][nextL] == false) { check[y][x][nextL] = true; q.push({y, x, nextL}); } for (int i = 1; i <= 3; i++) { int nx = x + dx[d] * i; int ny = y + dy[d] * i; if (1 <= ny && ny <= M && 1 <= nx && nx <= N) { if (map[ny][nx] == 1) { break; } if (check[ny][nx][d] == false) { check[ny][nx][d] = true; q.push({ny, nx, d}); } } } } num++; // for (int i = 1; i <= M; i++) { // for (int j = 1; j <= N; j++) { // cout << check[i][j][3] << " "; // } // cout << endl; // } // cout << endl; }}

0

1707 이분 그래프

링크https://www.acmicpc.net/problem/1707 채점 현황 전체 소스 코드#include <iostream>#include <vector>using namespace std;int T, V, E;vector<vector<int>> arr;bool check[20002];bool colorCheck[20002];int color[20002];void paintColor(int cnt, int cntColor) { for (int i = 0; i < arr[cnt].size(); i++) { int next = arr[cnt][i]; if (check[next] == false) { if (cntColor == 1) { color[next] = 2; check[next] = true; paintColor(next, 2); } else { color[next] = 1; check[next] = true; paintColor(next, 1); } } }}bool confirmColor(int cnt) { bool isTrue = true; for (int i = 0; i < arr[cnt].size(); i++) { int next = arr[cnt][i]; if (color[cnt] != color[next]) { if (colorCheck[next] == false) { colorCheck[next] = true; isTrue = confirmColor(next); } } else { return false; } } return isTrue;}int main(void) { cin >> T; while (T--) { cin >> V >> E; arr = vector<vector<int>>(V + 1); for (int i = 0; i < E; i++) { int x, y; cin >> x >> y; arr[x].push_back(y); arr[y].push_back(x); } for (int i = 1; i <= V; i++) { if (check[i] == false) { check[i] = true; color[i] = 1; paintColor(i, 1); } } bool isTrue; for (int i = 1; i <= V; i++) { if (colorCheck[i] == false) { colorCheck[i] = true; isTrue = confirmColor(i); if (isTrue == false) { cout << "NO" << '\n'; break; } } } if (isTrue == true) { cout << "YES" << '\n'; } for (int i = 1; i <= V; i++) { check[i] = 0; colorCheck[i] = false; color[i] = 0; } }}

0

백준 1600 - 말이 되고픈 원숭이

링크https://www.acmicpc.net/problem/1600 체점 현황 문제 풀이 말처럼 뛸 수 있는 횟수(k), width, height를 입력 받는다. field에 대한 정보를 입력 받는다. (0, 0)에서 시작해 (width-1, height-1)까지 갈 수 있는 최소 횟수를 탐색한다. 원숭이가 움직일 수 있는 방법은 두가지가 존재한다. 말처럼 뛸 수 있는 방법(k내의 횟수에서) 상하좌우로 움직일 수 있는 방법 말이 (width-1, height-1)에 도착하면 그 횟수를 반환한다. 만약 도착하지 못할 경우 -1을 반환한다. 말이 움직인 횟수를 출력해준다. 전체 소스 코드#include <bits/stdc++.h>using namespace std;int numOfKnight;int width, height;int field[202][202];bool check[31][202][202];int dx[4] = {1, -1, 0, 0};int dy[4] = {0, 0, 1, -1};int horse_dx[8] = {1, 2, 2, 1, -1, -2, -2, -1};int horse_dy[8] = {2, 1, -1, -2, -2, -1, 1, 2};struct point { int k; int y; int x;};int bfs(int y, int x) { check[0][y][x] = true; queue<point> q; q.push({0, y, x}); int count = 0; while (!q.empty()) { int q_size = q.size(); while (q_size--) { int cntK = q.front().k; int cntY = q.front().y; int cntX = q.front().x; q.pop(); if (cntY == height - 1 && cntX == width - 1) { return count; } if (cntK < numOfKnight) { for (int i = 0; i < 8; i++) { int ny = cntY + horse_dy[i]; int nx = cntX + horse_dx[i]; if (0 > ny || ny >= height || 0 > nx || nx >= width) continue; if (field[ny][nx] == 0 && check[cntK + 1][ny][nx] == false) { check[cntK + 1][ny][nx] = true; q.push({cntK + 1, ny, nx}); } } } for (int i = 0; i < 4; i++) { int ny = cntY + dy[i]; int nx = cntX + dx[i]; if (0 > ny || ny >= height || 0 > nx || nx >= width) continue; if (field[ny][nx] == 0 && check[cntK][ny][nx] == false) { check[cntK][ny][nx] = true; q.push({cntK, ny, nx}); } } } count++; } return -1;}int main(void) { cin >> numOfKnight >> width >> height; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { cin >> field[i][j]; } } int minValueOfMove = bfs(0, 0); cout << minValueOfMove << '\n'; return 0;}

0

백준 1260 - DFS와 BFS

링크https://www.acmicpc.net/problem/1260 문제 풀이그래프탐색에 있어 가장 기본적인 DFS, BFS를 사용해볼 수 있는 유형이다. 좌표 자체가 존재하지 않아 1차원적인 check방식을 통해 탐색해 나간다. cpp 코드#include <bits/stdc++.h>using namespace std;// 점점의 개수 : N, 간산의 개수 M, 탐색을 시작할 정점의 번호 Vint N, M, V;bool check_dfs[1010];bool check_bfs[1010];int graph[1010][1010];void bfs(int start) { queue<int> q; q.push(start); check_bfs[start] = true; while (!q.empty()) { int cnt = q.front(); q.pop(); cout << cnt << ' '; for (int i = 1; i <= N; i++) { if (graph[cnt][i] == 1 && check_bfs[i] == false) { check_bfs[i] = true; q.push(i); } } }}void dfs(int depth, int cnt) { check_dfs[cnt] = true; if (N <= depth) { return; } cout << cnt << ' '; for (int i = 1; i <= N; i++) { if (graph[cnt][i] == 1 && check_dfs[i] == false) { dfs(depth + 1, i); } }}int main(void) { cin >> N >> M >> V; for (int i = 0; i < M; i++) { int a, b; cin >> a >> b; graph[a][b] = 1; graph[b][a] = 1; } dfs(0, V); cout << '\n'; bfs(V); return 0;} java 코드import java.io.IOException;import java.util.LinkedList;import java.util.Queue;import java.util.Scanner;public class Main { static int n, m, v; static int map[][]; static boolean bfs_check[]; static boolean dfs_check[]; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); v = sc.nextInt(); map = new int[n + 1][n + 1]; for (int i = 0; i < m; i++) { int from, to; from = sc.nextInt(); to = sc.nextInt(); map[from][to] = 1; map[to][from] = 1; } bfs_check = new boolean[n + 1]; dfs_check = new boolean[n + 1]; dfs(v); System.out.println(); bfs(v); sc.close(); } static void dfs(int node) { System.out.print(Integer.toString(node) + ' '); dfs_check[node] = true; for (int i = 1; i <= n; i++) { if (map[node][i] == 1 && dfs_check[i] == false) { dfs(i); } } } static void bfs(int start) { Queue<Integer> q = new LinkedList<Integer>(); q.offer(start); bfs_check[start] = true; System.out.print(Integer.toString(start) + ' '); while (!q.isEmpty()) { int cnt = q.remove(); for (int i = 1; i <= n; i++) { if (map[cnt][i] == 1 && bfs_check[i] == false) { bfs_check[i] = true; q.offer(i); System.out.print(Integer.toString(i) + ' '); } } } }} python 코드

0

백준 1012 - 유기농 배추

링크https://www.acmicpc.net/problem/1012 채점 현황 문제 풀이전형적인 색칠하기 유형히다.이 문제는 testcase문제이기 때문에 각 case마다 데이터를 초기화 해줘야 한다. field를 탐색하면서 배추가 심어져 있는 위치를 찾는다. 배추가 심어져 있는 곳을 찾았다면 이전에 탐색을 했는지 확인한다. 탐색한 적이 없다면 다음으로 넘어간다. 탐색한 적이 있다면 1로 돌아간다. 배추가 심어져 있는 주변에 다른 배추들이 있는지 탐색한다. 탐색횟수가 배추 흰 지렁이의 갯수가 된다. BFS를 이용한 코드