3 回答

TA貢獻1851條經驗 獲得超4個贊
給定一個高度和寬度可能不相等的二維數組(矩陣)
但是您正在對高度和寬度始終相同的矩陣進行操作
for(int row = 0; row<matrix.length; row++){ for(int col = 0; col<matrix.length; col++){ .. }}
你應該像下面這樣使用尺寸,我想剩下的就足夠了..
for(int row = 0; row<matrix.length; row++){ for(int col = 0; col<matrix[row].length; col++){ .. }}
并且更改也需要應用到函數“isValid”中
public static boolean isValid(int row, int col,int[][] matrix){ return (row >= 0 && row < matrix.length) && (col >= 0 && col < matrix[row].length); }

TA貢獻1851條經驗 獲得超3個贊
轉換count為局部變量并累加:
static int traverseMatrix(int row, int col, int[][] matrix, boolean[][] visitStatus) {
if (visitStatus[row][col] || matrix[row][col] == 0) {
return 0;
}
visitStatus[row][col] = true;
int count = 1;
if (isValid(row, col - 1, matrix)) {
count += traverseMatrix(row, col - 1, matrix, visitStatus);
}
...
return count;
}

TA貢獻1850條經驗 獲得超11個贊
我的解決方案是用 C# 編寫的,但它與 Java 類似:
您可以將 List 替換為 ArrayList
代碼:
public static List<int> RiverSizes(int[,] matrix)
{
var sizes = new List<int>();
bool[,] visited = new bool[matrix.GetLength(0), matrix.GetLength(1)];
for (int row = 0; row < matrix.GetLength(0); row++)
for (int col = 0; col < matrix.GetLength(1); col++)
if (visited[row, col])
continue;
else
Traverse(matrix, row, col, visited, sizes);
return sizes;
}
public static void Traverse(int[,] matrix, int row, int col, bool[,] visited, List<int> sizes)
{
int currentSize = 0;
var toExplore = new List<int[]>
{
new int[] { row, col }
};
while (toExplore.Count > 0)
{
var current = toExplore[^1];
toExplore.RemoveAt(toExplore.Count - 1);
row = current[0];
col = current[1];
if (visited[row, col])
continue;
visited[row, col] = true;
if (matrix[row, col] == 0)
continue;
currentSize++;
foreach (int[] item in GetNeighbours(matrix, row, col, visited))
toExplore.Add(item);
}
if (currentSize > 0)
sizes.Add(currentSize);
}
public static List<int[]> GetNeighbours(int[,] matrix, int row, int col, bool[,] visited)
{
List<int[]> neighbours = new List<int[]>();
if (row > 0 && !visited[row - 1, col])
neighbours.Add(new int[] { row - 1, col });
if (row < matrix.GetLength(0) - 1 && !visited[row + 1, col])
neighbours.Add(new int[] { row + 1, col });
if (col > 0 && !visited[row, col - 1])
neighbours.Add(new int[] { row, col - 1 });
if (col < matrix.GetLength(1) - 1 && !visited[row, col + 1])
neighbours.Add(new int[] { row, col + 1 });
return neighbours;
}
希望對您有幫助^-^
添加回答
舉報