```
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
for(int i = 0;i<rooms.size();++i)
for(int j = 0;j<rooms[0].size();++j)
if(rooms[i][j] == 0)
dfs(rooms, 0, i, j);
}
void dfs(vector<vector<int>> & rooms, int level, int x, int y)
{
if(x < 0 || y < 0 || x >= rooms.size() || y >= rooms[0].size()||rooms[x][y] < level)
return;
rooms[x][y] = level++;
dfs(rooms,level, x-1,y);
dfs(rooms,level, x+1, y);
dfs(rooms, level, x, y-1);
dfs(rooms, level, x,y+1);
}
};
```