如何封装二维数组单元格周边操作代码为函数或简化实现?
封装二维数组单元格及周边元素操作的方案
当然可以封装成通用函数,核心是把重复的周边元素遍历+边界判断逻辑抽出来,把不同的业务操作(当前单元格处理、周边元素处理)作为回调传入,这样就能适配各种类似结构的需求。
第一步:写通用遍历函数
这个函数负责处理坐标合法性检查、遍历8个方向的周边元素,把具体的操作逻辑交给外部传入的回调:
// 以JS为例,其他语言逻辑一致,仅需调整语法细节 function processCellAndNeighbors(arr, targetRow, targetCol, handleCurrent, handleNeighbor) { const rows = arr.length; if (rows === 0) return; const cols = arr[0].length; // 检查目标单元格是否在数组范围内 if (targetRow < 0 || targetRow >= rows || targetCol < 0 || targetCol >= cols) { return; } // 执行当前单元格的自定义操作 handleCurrent(arr[targetRow][targetCol], targetRow, targetCol, arr); // 定义8个周边方向的偏移量 const directions = [ [-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1] ]; // 遍历所有周边元素并执行自定义操作 for (const [dr, dc] of directions) { const neighborRow = targetRow + dr; const neighborCol = targetCol + dc; if (neighborRow >= 0 && neighborRow < rows && neighborCol >=0 && neighborCol < cols) { handleNeighbor(arr[neighborRow][neighborCol], neighborRow, neighborCol, arr); } } }
第二步:用现有需求调用通用函数
针对你提到的mapmines数组操作——当目标位置不为9时设为9,周边元素不为9则自增,直接传入对应的回调即可:
// 处理当前单元格的回调 function handleCurrentMine(cell, row, col, arr) { if (cell !== 9) { arr[row][col] = 9; } } // 处理周边元素的回调 function handleNeighborMine(cell, row, col, arr) { if (cell !== 9) { arr[row][col]++; } } // 调用示例:rndr、rndc为目标坐标 processCellAndNeighbors(mapmines, rndr, rndc, handleCurrentMine, handleNeighborMine);
第三步:适配其他类似结构的需求
如果有另一段结构类似但操作不同的代码,比如「当目标单元格不为0时设为0,周边元素不为0则减1」,只需编写新的回调函数,复用通用遍历逻辑:
function handleCurrentZero(cell, row, col, arr) { if (cell !== 0) { arr[row][col] = 0; } } function handleNeighborZero(cell, row, col, arr) { if (cell !== 0) { arr[row][col]--; } } // 直接调用通用函数 processCellAndNeighbors(yourOtherArray, targetRow, targetCol, handleCurrentZero, handleNeighborZero);
简化的优势
- 避免重复编写8个方向遍历、边界判断的冗余代码
- 核心遍历逻辑和业务操作解耦,后续修改操作逻辑只需调整回调,不用动遍历部分
- 代码可读性更高,一眼就能明确当前执行的业务操作
内容的提问来源于stack exchange,提问作者max barcon
相关产品推荐
相关产品推荐

