【发布时间】:2026-02-11 04:10:02
【问题描述】:
【问题讨论】:
-
你的意思是你不知道如何在矩阵中搜索列来找到相邻的 1? Stack Overflow 真的不是我们为你做你的工作。这是关于我们帮助您改进自己的工作。请阅读*.com/help/how-to-ask,并相应地编辑您的问题。
标签: java algorithm matrix graph-algorithm adjacency-matrix
【问题讨论】:
标签: java algorithm matrix graph-algorithm adjacency-matrix
这更多属于脑筋急转弯类别。
对于小型矩阵,我们只需逐列访问它。
假设输入是一个二维整数数组,输出是以下类的列表:
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。然后,我将遍历列而不再次计算。
【讨论】: