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

请求二维字符数组中连续相同字符最长长度的算法或伪代码

Alright, let's walk through how to solve this grid problem where we need to find the longest run of identical consecutive characters (either horizontal or vertical). Below is a straightforward algorithm and pseudocode that's easy to translate into C:

整体算法思路

The core idea is to check every possible horizontal and vertical sequence in the grid, keeping track of the longest consecutive streak we find:

  • Start with a maximum count of 1 (since even a single character counts as a streak of 1)
  • Horizontal check: Iterate through each row, comparing each character to the one before it. Count consecutive matches and update the maximum streak whenever we find a longer one.
  • Vertical check: Do the same for each column, comparing each character to the one above it. Again, update the maximum streak as needed.
  • After checking all rows and columns, the maximum count will be our answer.
伪代码实现
// Read number of test cases
READ T

FOR each test case in 1..T:
    // Read grid dimensions: n rows, m columns
    READ n, m
    
    // Initialize and populate the grid
    CREATE 2D array grid[n][m]
    FOR i from 0 to n-1:
        READ row (a string of m lowercase characters)
        FOR j from 0 to m-1:
            grid[i][j] = row[j]
    
    // Set initial maximum streak to 1 (minimum possible value)
    max_streak = 1

    // Check horizontal consecutive characters
    FOR each row i in 0..n-1:
        current_streak = 1
        FOR each column j in 1..m-1:
            IF grid[i][j] == grid[i][j-1]:
                current_streak += 1
                // Update max if current streak is longer
                IF current_streak > max_streak:
                    max_streak = current_streak
            ELSE:
                // Reset streak when characters don't match
                current_streak = 1

    // Check vertical consecutive characters
    FOR each column j in 0..m-1:
        current_streak = 1
        FOR each row i in 1..n-1:
            IF grid[i][j] == grid[i-1][j]:
                current_streak += 1
                IF current_streak > max_streak:
                    max_streak = current_streak
            ELSE:
                current_streak = 1

    // Output the result for this test case
    PRINT max_streak

Key Notes

  • We initialize max_streak to 1 to handle edge cases where all characters in the grid are unique (so the longest streak is 1).
  • Separating horizontal and vertical checks keeps the logic simple and easy to debug.
  • We update max_streak immediately whenever we find a longer streak to ensure we never miss the maximum value.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:57:07