
图94603-1:
个人使用ai的一些体验感想供大家分享与指正
问了ChatGPT一个问题:
node.js实现判断一个格子是否可达?
他的回答是:
要判断一个格子是否可达,可以使用广度优先搜索(BFS)算法来实现。
以下是一个用 Node.js 实现判断格子可达性的示例:
function isReachable(grid, startRow, startCol, endRow, endCol) { const queue = [{ row: startRow, col: startCol }]; const visited = new Set(); const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; while (queue.length > 0) { const current = queue.shift(); if (current.row === endRow && current.col === endCol) { return true; // 找到目标格子,可达 } visited.add(`${current.row},${current.col}`); for (const [dx, dy] of directions) { const newRow = current.row + dx; const newCol = current.col + dy; if ( newRow >= 0 && newRow < grid.length && newCol >= 0 && newCol < grid[0].length && !visited.has(`${newRow},${newCol}`) && grid[newRow][newCol] !== 0 ) { queue.push({ row: newRow, col: newCol }); } } } return false; // 无法找到可达路径 } // 示例使用 const grid = [ [1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1], [1, 0, 0, 0] ]; const startRow = 0; const startCol = 0; const endRow = 3; const endCol = 3; const reachable = isReachable(grid, startRow, startCol, endRow, endCol); console.log('目标格子是否可达:', reachable);在上述示例中,grid 是一个二维数组,表示网格状的地图。数字 1 表示可达的格子,数字 0 表示不可达的障碍物。startRow、startCol 分别表示起点格子的行和列,endRow、endCol 分别表示目标格子的行和列。函数 isReachable 使用了广度优先搜索算法(BFS)来搜索路径,通过队列 queue 记录待遍历的格子,使用 visited 判断格子是否已被访问。算法从起点开始,按照上下左右四个方向依次遍历相邻的格子,并将其入队。直到找到目标格子或队列为空时结束。若找到可达路径,返回 true;否则,返回 false。
在实际应用中,可能需要考虑更复杂的算法和数据结构,如 A* 算法、深度优先搜索(DFS)等,以处理更复杂的情况,并提高寻路的效率和精确度。
经过实际的测试发现,这个算法是可行的,个人对于ai的感觉是,可以对工作起到辅助提高效率,让程序员更专注于业务实现,当然,同时也考验程序员对ai的驾驭能力,你首先得会使用会问问题,同时,你还需要对ai生成的代码有辨别对错优劣的能力,不然,盲目的把ai生成的代码放入到实际的项目中是会有额外的风险。
来源:今日头条
作者:coderDonkey
点赞:0
评论:0
标题:程序员使用ai实录
原文:https://www.toutiao.com/article/7196887962435519016
侵权告知删除:yangzy187@126.com
转载请注明:网创网 www.netcyw.cn/b94603.html










