```
void dfs(vector<vector<int>>& rooms, int i, int j, int len) {
if (i < 0 || j < 0 || i >= rooms.size() || j >= rooms[0].size() || rooms[i][j] == -1 || len > rooms[i][j]) return;
rooms[i][j] = len;
dfs(rooms, i, j + 1, len + 1);
dfs(rooms, i, j - 1, len + 1);
dfs(rooms, i + 1, j, len + 1);
dfs(rooms, i - 1, j, len + 1);
}
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, i, j, 0);
}
}
}
```