본인의 풀이는 현재 보드에서 나올 수 있는 모든 가지수를 구해서 최소뒤집는 횟수를 리턴해주는 방식이다.
하지만 좋은 풀이가 아니므로 아래의 다른 코드를 참고하자.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int answer = -1;
int n,m;
void flipRow(int idx, vector<vector<int>> *board) {
for(int i=0; i<m; i++) {
if ((*board)[idx][i] == 0) (*board)[idx][i] = 1;
else (*board)[idx][i] = 0;
}
}
void flipCol(int idx, vector<vector<int>> *board) {
for(int i=0; i<n; i++) {
if ((*board)[i][idx] == 0) (*board)[i][idx] = 1;
else (*board)[i][idx] = 0;
}
}
void isSameBoard(vector<vector<int>> board, vector<int> flipRowIdx, vector<int> flipColIdx, vector<vector<int>> target) {
for (auto idx : flipRowIdx) flipRow(idx, &board);
for (auto idx : flipColIdx) flipCol(idx, &board);
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if (board[i][j] != target[i][j]) return ;
int res = flipRowIdx.size() + flipColIdx.size();
if (answer == -1) answer = res;
else answer = min(answer, res);
}
void dfs(int idx, int num, vector<int> tmp, vector<vector<int>> *flipIdxs) {
(*flipIdxs).push_back(tmp);
for (int i=idx; i<num; i++) {
tmp.push_back(i);
dfs(i+1, num, tmp, flipIdxs);
tmp.pop_back();
}
}
int solution(vector<vector<int>> beginning, vector<vector<int>> target) {
n = beginning.size();
m = beginning[0].size();
vector<vector<int>> flipRowIdxs, flipColIdxs;
dfs(0,n,{}, &flipRowIdxs);
dfs(0,m,{}, &flipColIdxs);
for (auto flipRowIdx : flipRowIdxs) {
for (auto flipColIdx : flipColIdxs) {
isSameBoard(beginning, flipRowIdx, flipColIdx, target);
}
}
return answer;
}
#include <vector>
#include <iostream>
using namespace std;
int solution(vector<vector<int>> beginning, vector<vector<int>> target) {
int answer=0;
int r_size=beginning.size(), c_size=beginning[0].size();
vector<vector<int>> board(r_size,vector<int>(c_size));
for(int i=0; i<r_size; i++)
for(int j=0; j<c_size; j++)
board[i][j]=beginning[i][j]^target[i][j];
int cnt=0, sum=0;
for(int i=0; i<c_size; i++) sum+=board[0][i];
for(int i=1; i<r_size; i++) {
bool o_flag=true, r_flag=true;
for(int j=0; j<c_size; j++) {
if((board[i][j]^0)!=board[0][j]) o_flag=false;
if((board[i][j]^1)!=board[0][j]) r_flag=false;
}
if (!o_flag) {
if(!r_flag) return -1;
else cnt++;
}
}
answer=min(cnt+sum,r_size-cnt+c_size-sum);
return answer;
}