You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从十字网格数据中获取答案的起始列、结束列及行号

解决方案

你的核心问题在于GetColumnStart方法未正确实现,导致无法定位答案在对应行的起始列。以下是针对不同网格数据结构的实现方案,并补充边界校验逻辑:

1. 网格每行是字符串(List<string> board)

如果网格以字符串列表存储(每行是完整字符串),可直接用String.IndexOf快速定位:

// 实现GetColumnStart方法
private int GetColumnStart(List<string> board, int rowIndex, string target)
{
    // 校验行索引有效性
    if (rowIndex < 0 || rowIndex >= board.Count)
        return -1;
    
    string currentRow = board[rowIndex];
    // 目标长度超过行长度,直接返回-1
    if (target.Length > currentRow.Length)
        return -1;
    
    // 精确匹配目标字符串的起始位置,找不到返回-1
    return currentRow.IndexOf(target, StringComparison.Ordinal);
}

2. 网格是二维字符数组(char[][] board)

如果网格是二维字符数组,先将行转为字符串再匹配:

private int GetColumnStart(char[][] board, int rowIndex, string target)
{
    if (rowIndex < 0 || rowIndex >= board.Length)
        return -1;
    
    char[] currentRow = board[rowIndex];
    if (target.Length > currentRow.Length)
        return -1;
    
    string rowStr = new string(currentRow);
    return rowStr.IndexOf(target, StringComparison.Ordinal);
}

3. 处理填字游戏的占位符场景(空白用.表示)

如果十字网格是填字游戏类型,存在空白占位符(比如.),需要匹配连续的可填充序列:

private int GetColumnStart(List<string> board, int rowIndex, string target)
{
    if (rowIndex < 0 || rowIndex >= board.Count || string.IsNullOrEmpty(target))
        return -1;
    
    string currentRow = board[rowIndex];
    int maxStartPos = currentRow.Length - target.Length;
    if (maxStartPos < 0)
        return -1;
    
    // 遍历每个可能的起始位置,逐字符匹配
    for (int i = 0; i <= maxStartPos; i++)
    {
        bool isMatch = true;
        for (int j = 0; j < target.Length; j++)
        {
            char boardChar = currentRow[i + j];
            // 占位符`.`可匹配任意字符,否则严格匹配
            if (boardChar != '.' && boardChar != target[j])
            {
                isMatch = false;
                break;
            }
        }
        if (isMatch)
            return i;
    }
    return -1;
}

补充原代码的边界校验

在循环前先校验答案数量和网格行数是否一致,避免索引越界:

List<AnswerPosition> answerPositions = new List<AnswerPosition>();

// 新增:校验答案数与网格行数匹配
if (answers.Count != board.Count)
{
    throw new ArgumentException("答案列表数量与网格行数不匹配");
}

for (int k = 0; k < rows; k++)
{
    string answer = answers[k];
    int colStart = GetColumnStart(board, k, answer);

    if (colStart >= 0)
    {
        answerPositions.Add(new AnswerPosition
        {
            Answer = answer,
            Row = k,
            ColumnStart = colStart,
            ColumnEnd = colStart + answer.Length - 1
        });
    }
}

内容的提问来源于stack exchange,提问作者rani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 18:05:36