알고리즘
백준 1941번 소문난 칠공주 C++
영춘권의달인
2022. 1. 9. 13:50
1. 백트래킹을 이용하여 7명의 학생을 모은 그룹을 모두 탐색한다.
2. 7명이 전부 붙어있는지 bfs를 이용해 확인한다.
3. 7명이 전부 붙어있다면 이다솜파의 학생이 4명 이상인지 확인해서 맞다면 ans를 1 증가시킨다.
tip : n번째 학생이라면 n/5, n%5를 통해 행과 열을 알아낼 수 있다. (n은 0부터 시작)
예를 들어 7번째 학생이라면 7/5 , 7%5 이므로 학생의 위치는 (1, 2) 라는 것을 알 수 있다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
vector<vector<char>> board(5, vector<char>(5));
vector<int> IDSP;
int ans = 0;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
bool bfs() {
vector<vector<bool>> found(5, vector<bool>(5, true));
for (int i = 0; i < 7; i++) {
int row = IDSP[i] / 5;
int col = IDSP[i] % 5;
found[row][col] = false;
}
int cnt = 0;
int idsp_n = 0;
queue<pair<int, int>> q;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (!found[i][j]) {
cnt++;
q.push({ i,j });
found[i][j] = true;
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (board[curr.first][curr.second] == 'S') {
idsp_n++;
}
for (int k = 0; k < 4; k++) {
int nextRow = curr.first + dRow[k];
int nextCol = curr.second + dCol[k];
if (nextRow < 0 || nextRow >= 5) continue;
if (nextCol < 0 || nextCol >= 5) continue;
if (found[nextRow][nextCol]) continue;
q.push({ nextRow, nextCol });
found[nextRow][nextCol] = true;
}
}
}
}
}
if (cnt > 1) return false;
if (idsp_n < 4) return false;
return true;
}
void BT(int num, int cnt) {
if (cnt >= 7) {
if (bfs()) ans++;
return;
}
for (int i = num; i < 25; i++) {
IDSP.push_back(i);
BT(i + 1, cnt + 1);
IDSP.pop_back();
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string str;
for (int i = 0; i < 5; i++) {
cin >> str;
for (int j = 0; j < 5; j++) {
board[i][j] = str[j];
}
}
BT(0, 0);
cout << ans;
};