【问题标题】:algorithm for finding the number of 1s in a matrix (only vertical 1s). The image is self explanatory that what i exactly want用于查找矩阵中 1 数量的算法(仅垂直 1)。图像是不言自明的,我到底想要什么
【发布时间】:2026-02-11 04:10:02
【问题描述】:

在矩阵中查找 1 的组需要算法,但 1 的组应该只包含垂直条目

【问题讨论】:

  • 你的意思是你不知道如何在矩阵中搜索列来找到相邻的 1? Stack Overflow 真的不是我们为你做你的工作。这是关于我们帮助您改进自己的工作。请阅读*.com/help/how-to-ask,并相应地编辑您的问题。

标签: java algorithm matrix graph-algorithm adjacency-matrix


【解决方案1】:

这更多属于脑筋急转弯类别。

对于小型矩阵,我们只需逐列访问它。

假设输入是一个二维整数数组,输出是以下类的列表:

class GroupIdentifier {
  int col;
  int rowStart;
  int colStart; 

  /* the corresponding getter/setter/constructor etc */
}

这是您要查找的功能:

int FIRST_ONE = 2;
int IN_GROUP = 1;
int OUT_GROUP = 0;

public List<GroupIdentifier> findVerticalGroupsOf1 (int[][] a, 
  int numRow, int numCol) {
  List<GroupIdentifier> answer = new ArrayList<GroupIdentifier>();
  for (col = 0; col < numCol; col = col + 1) {
    // let's create the tempArr holding the current col
    int[] tempArr = new int[numRow];
    for (row = 0; row < numRow; row = row + 1 =) {
      tempArr[row] = a[row][col];
    }
    // let's find the groups
    // first, init the state
    int state = (tempArr[0] == 1) ? FIRST_ONE : OUT_GROUP;
    int start = (state == FIRST_ONE) ? 0 : -1;
    // I see this problem as a simple state-machine
    // We have three states: FIRST_ONE encountered (0 to 1),
    // still tracking the 1s IN_GROUP ... (1 to 1) and 
    // get OUT_GROUP (1 to 0). 
    // the switch case in the following loop does exactly that.
    // So, whenever we get an OUT_GROUP event, we get an answer.
    for (int i = 1; i < numRow; i = i + 1) { // edit: changed to numRow as
                                             // it was a typo error
      switch (state) : 
      case FIRST_ONE :
        if (tempArr[i] == 0)
          state = OUT_GROUP;
        else 
          state = IN_GROUP; 
        break;
      case IN_GROUP :
        if (tempArr[i] == 0) {
          GroupIdentifier gi = new GroupIdentifier (col, start, i - 1);
          answer.add(gi); 
        }
        break; 
      case OUT_GROUP :
        if (tempArr[i] == 1) {
          start = i; 
          state = FIRST_ONE;
        } 
        break; 
    }

  }
  // since this question looks like homework,
  // i will leave out the boundary case handling
  // here. it's not that hard; just copy/paste the
  // switch statement and fondle around.
  return answer; 
}

作为一名计算机科学家,我想办法优化它。

对于较大的矩阵,我要做的是预先计算 tempArr 的所有组合并将它们存储为 Integer --> List map。然后,我将遍历列而不再次计算。

【讨论】:

  • @EdwardAung 你能解释一下这段代码吗?我对用于垂直分组的逻辑感到困惑。如果你能用Java编写完整的代码会更好。谢谢
  • @user8409309 ... 编辑了答案以包括解释代码的 cmets(并更正了拼写错误)。而且我的代码是纯 Java 的(甚至不使用任何已知的库)。
  • 你能把完整的java代码发给我吗?我解决了这个功能,但我无法实现它。谢谢
最近更新 更多