3 回答

TA貢獻1777條經(jīng)驗 獲得超10個贊
我知道您正在嘗試使用遞歸,但是使用 LINQ 進行此練習(xí)要簡單得多。
如果你從這個開始:
int[,] twoDArr = new int[,]
{
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 },
};
int[][]通過這樣做可以很容易地將其轉(zhuǎn)換為 a :
int[][] rows =
twoDArr
.Cast<int>() // flattens to one dimension
.Select((value, index) => new { value, index })
.GroupBy(x => x.index / twoDArr.GetLength(1), x => x.value)
.Select(x => x.ToArray())
.ToArray();
在.GroupBy關(guān)鍵的是x.index / twoDArr.GetLongLength(1),這樣的從零開始的每一行的整數(shù)。
這給出了:
現(xiàn)在你可以簡單地這樣做:
int result = rows.First().Sum() + rows.Last().Sum();
我從我的樣本數(shù)據(jù)中得到的結(jié)果是18
(這是第一行和最后一行的正確總和)。

TA貢獻1852條經(jīng)驗 獲得超7個贊
這與您的代碼無關(guān)。這只是我對第一行和最后一行進行遞歸求和的版本。我希望它有幫助。
int SumFirstLastRows(int[,] twoD)
{
// we need some pointer information on when to start and end,
// let's use column and row number, starting from 0,0
return SumRecursive(twoD, 0, 0);
}
// this is a recursive method, which goes for each row and column recursively,
// however it only takes the sum of first and last rows' numbers
int SumRecursive(int[,] twoD, int column, int row)
{
// determine the max row and column, to know when to end
int maxRows = twoD.GetLength(0);
int maxColumns= twoD.GetLength(1);
if (row == maxRows)
{
// we are at the end of the rows, end everything
return 0;
}
else if (column == maxColumns)
{
// we are at the end of column, switch to the next row instead
return SumRecursive(twoD, 0, row + 1);
}
if ((row== 0 || row == maxRows-1) && column < maxColumns)
{
// only for the first or last row: current number + next column sum
return twoD[row, column] + SumRecursive(twoD, column + 1, row);
}
else if(column < maxColumns)
{
// not the first or last row, so just skip to the next column
return SumRecursive(twoD, column + 1, row);
}
return 0;
}
測試:
int[,] twod = new int[3,4]
{ {1,2,3,4 },
{5,6,7,8 },
{9,10,11,12 }
};
int recursiveTest = SumFirstLastRows(twod);
int forVerification = 1 + 2 + 3 + 4 + 9 + 10 + 11 + 12;
bool isThisCorrect = recursiveTest == forVerification; // return true!
- 3 回答
- 0 關(guān)注
- 272 瀏覽
添加回答
舉報