返回介绍

solution / 2100-2199 / 2128.Remove All Ones With Row and Column Flips / README_EN

发布于 2024-06-17 01:03:09 字数 4150 浏览 0 评论 0 收藏 0

2128. Remove All Ones With Row and Column Flips

中文文档

Description

You are given an m x n binary matrix grid.

In one operation, you can choose any row or column and flip each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).

Return true_ if it is possible to remove all _1_'s from _grid using any number of operations or false otherwise.

 

Example 1:

Input: grid = [[0,1,0],[1,0,1],[0,1,0]]
Output: true
Explanation: One possible way to remove all 1's from grid is to:
- Flip the middle row
- Flip the middle column

Example 2:

Input: grid = [[1,1,0],[0,0,0],[0,0,0]]
Output: false
Explanation: It is impossible to remove all 1's from grid.

Example 3:

Input: grid = [[0]]
Output: true
Explanation: There are no 1's in grid.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is either 0 or 1.

Solutions

Solution 1

class Solution:
  def removeOnes(self, grid: List[List[int]]) -> bool:
    s = set()
    for row in grid:
      t = tuple(row) if row[0] == grid[0][0] else tuple(x ^ 1 for x in row)
      s.add(t)
    return len(s) == 1
class Solution {
  public boolean removeOnes(int[][] grid) {
    Set<String> s = new HashSet<>();
    int n = grid[0].length;
    for (var row : grid) {
      var cs = new char[n];
      for (int i = 0; i < n; ++i) {
        cs[i] = (char) (row[0] ^ row[i]);
      }
      s.add(String.valueOf(cs));
    }
    return s.size() == 1;
  }
}
class Solution {
public:
  bool removeOnes(vector<vector<int>>& grid) {
    unordered_set<string> s;
    for (auto& row : grid) {
      string t;
      for (int x : row) {
        t.push_back('0' + (row[0] == 0 ? x : x ^ 1));
      }
      s.insert(t);
    }
    return s.size() == 1;
  }
};
func removeOnes(grid [][]int) bool {
  s := map[string]bool{}
  for _, row := range grid {
    t := []byte{}
    for _, x := range row {
      if row[0] == 1 {
        x ^= 1
      }
      t = append(t, byte(x)+'0')
    }
    s[string(t)] = true
  }
  return len(s) == 1
}
function removeOnes(grid: number[][]): boolean {
  const s = new Set<string>();
  for (const row of grid) {
    if (row[0] === 1) {
      for (let i = 0; i < row.length; i++) {
        row[i] ^= 1;
      }
    }
    const t = row.join('');
    s.add(t);
  }
  return s.size === 1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文