题目
统计子岛屿 问题,如图

解法
对表格2,采用递归的方法遍历岛屿,在递归时检查一下表格一对应位置是不是陆地。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
   | 
 
 
 
  var countSubIslands = function (grid1, grid2) { 	m = grid1.length; 	n = grid1[0].length; 	count = 0;
  	const dfs = (row, col) => { 		if (row < 0 || row >= m || col < 0 || col >= n || grid2[row][col] != 1) return true; 		grid2[row][col] = 2; 		let temp = grid1[row][col] === 1; 		temp = dfs(row + 1, col) && temp; 		temp = dfs(row - 1, col) && temp; 		temp = dfs(row, col + 1) && temp; 		temp = dfs(row, col - 1) && temp; 		return temp; 	};
  	for (let row = 0; row < m; row++) { 		for (let col = 0; col < n; col++) { 			if (grid2[row][col] === 1 && dfs(row, col)) { 				count++; 			} 		} 	} 	return count; };
 
  | 
低级错误
问题来了,在递归时需要一个变量保存该点所在岛屿是否是子岛。在上面的代码中,temp这一变量就是这个作用。但是在错误版本中,我把let temp = grid1[row][col] === 1错误的丢掉了let关键字——这使得所有栈中共享一个temp,赋值会改变其他层中temp被覆盖,导致错误。
反思
js的函数中,变量可以不声明而直接赋值,这一点导致我写着写着就以为自己在写python,排查时完全没想到是语法错误。警钟长鸣!