【发布时间】:2021-04-24 08:43:58
【问题描述】:
问题描述:https://leetcode.com/problems/number-of-islands/
基本上你有一个1和0的矩阵,你需要计算有多少组1。
尽管有许多打印语句,但我无法弄清楚为什么这段代码不起作用。 我正在遍历矩阵,每当我看到一个矩阵时,我都会进行深度优先搜索并将该 1 加上围绕它的所有 1 变为 0 - 以将这些节点标记为已访问。
我错过了什么?
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
//System.out.println(grid[i][j]);
if(grid[i][j] == '1') {
// System.out.println("i = " + i);
// System.out.println("j = " + j);
countIslands(grid, i, j);
count++;
}
}
}
return count;
}
public static void countIslands(char[][] grid, int sr, int sc) {
grid[sr][sc] = '0';
final int[][] SHIFTS = {
{0,1}, //move right
{1,0}, //move down
{0,-1}, //move left
{-1,0} //move up
};
for(int[] shift : SHIFTS) {
sr = sr + shift[0];
sc = sc + shift[1];
if(moveValid(grid, sr, sc)) {
countIslands(grid, sr, sc);
}
}
}
public static boolean moveValid(char[][] grid, int sr, int sc) {
if(sr >= 0 && sr < grid.length && sc >= 0 && sc < grid[sr].length && grid[sr][sc] == '1') {
return true;
}
return false;
}
}
【问题讨论】:
-
请将您的代码设为minimal reproducible example:发布硬编码数据和预期结果。另见What is a debugger and how can it help me diagnose problems?
标签: java recursion depth-first-search