标签:article ++ div details span arc lan 条件判断 dfs
错误版本:
条件判断顺序写错:grid[x][y] == ‘0‘ || x < 0 || x >= length || y < 0 || y >= width
这种写法要报数组越界的错误,因为grid[x][y]会先访问,实际上x、y这个时候可能就越界了,grid[x][y]必须放在这几个越界判断的后面
class Solution { public: int numIslands(vector<vector<char>>& grid) { int length = grid.size(); if(length <= 0) return 0; int width = grid[0].size(); int count = 0; for(int i = 0;i < length;i++){ for(int j = 0;j < width;j++){ if(grid[i][j] == ‘1‘){ search(grid,i,j,length,width); count++; } } } return count; } void search(vector<vector<char>>& grid,int x,int y,int length,int width){ if(x < 0 || x >= length || y < 0 || y >= width || grid[x][y] == ‘0‘) return; grid[x][y] = ‘0‘; search(grid,x-1,y,length,width); search(grid,x+1,y,length,width); search(grid,x,y-1,length,width); search(grid,x,y+1,length,width); } };
整体思路,从第一点开始找1,如果找到1,把所有的与这个1相连的1置为0,因为这些1与这个1属于同一个岛屿,用dfs去找把所有的1找到
https://blog.csdn.net/xudli/article/details/45912547
标签:article ++ div details span arc lan 条件判断 dfs
原文地址:https://www.cnblogs.com/ymjyqsx/p/9784453.html