第一行必W,最后一行必R,对中间的各行符号进行枚举,固定了顺序且去了重复
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n, m;
char color[5] = {'W', 'B', 'R'};
char a[55][55];
vector<int> result;
bool visit[55];
int last;
int cnt;
int temp_breadth;
int temp_depth;
vector<char> check;
void dfs(int depth, int last);
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
dfs(0, 0);
int row1 = 0, rown = 0;
for (int i = 1; i <= m; i++) {
if (a[1][i] != 'W') {
row1++;
}
if (a[n][i] != 'R') {
rown++;
}
}
sort(result.begin(), result.end());
cout << result[0] + row1 + rown;
return 0;
}
bool is_flag(vector<char> &check) {
for (int i = 0; i <= check.size() - 1; i++) {
if (check[i] == 'B') {
return true;
}
}
return false;
}
void dfs(int depth, int last) {
if (depth >= n - 2) {
if (is_flag(check)) {
result.push_back(cnt);
}
return ;
}
char last_c = '0';
for (int i = last; i <= 2; i++) {
if (color[i] != last_c ) {
for (int j = 1; j <= m; j++) {
if (a[depth + 2][j] != color[i]) {
cnt++;
}
}
check.push_back(color[i]);
last_c = color[i];
temp_depth = cnt;
dfs(depth + 1, i);
cnt = temp_depth;
check.pop_back();
}
}
}