1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.cpp 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O((m * n) * 2^(m * n))
// Space: O((m * n) * 2^(m * n))
class Solution {
public:
int minFlips(vector<vector<int>>& mat) {
static const vector<pair<int, int>> directions{{0, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int start = 0;
for (int r = 0; r < mat.size(); ++r) {
for (int c = 0; c < mat[0].size(); ++c) {
start |= mat[r][c] << r * mat[0].size() + c;
}
}
queue<pair<int, int>> q({{start, 0}});
unordered_set<int> lookup = {start};
while (!q.empty()) {
const auto [state, step] = q.front(); q.pop();
if (!state) {
return step;
}
for (int r = 0; r < mat.size(); ++r) {
for (int c = 0; c < mat[0].size(); ++c) {
int new_state = state;
for (const auto& [dr, dc] : directions) {
const auto& [nr, nc] = make_pair(r + dr, c + dc);
if (0 <= nr && nr < mat.size() &&
0 <= nc && nc < mat[0].size()) {
new_state ^= 1 << nr * mat[0].size() + nc;
}
}
if (lookup.count(new_state)) {
continue;
}
lookup.emplace(new_state);
q.emplace(new_state, step + 1);
}
}
}
return -1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助