Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions 01-matrix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
queue<pair<int, int>> zeroes;
int n = mat.size();
int m = mat[0].size();

vector<vector<int>> dist(n, vector<int>(m,INT_MAX));
unordered_set<string> us;

for (int i=0;i<mat.size();i++) {
for (int j=0;j<mat[0].size();j++) {
if (mat[i][j] == 0) {
zeroes.push({i,j});
dist[i][j] = 0;
}
}
}

auto getKeys = [](int x, int y) -> string {
return to_string(x) + "," + to_string(y);
};

auto visited = [&](int x, int y) {
string key = getKeys(x, y);
if (us.find(key) == us.end()) {
us.insert(key);
return true;
}
return false;
};

auto isSafe = [&](int newX, int newY){
if (newX >=0 && newY >=0 && newX < mat.size() && newY < mat[0].size()) {
return true;
}
return false;
};

auto addAdjacent = [&](pair<int, int> p) -> void {
vector<vector<int>> dirs = {{1,0}, {-1,0} ,{0, 1} , {0, -1}};
for (int i=0;i<dirs.size();i++) {
int newX = p.first + dirs[i][0];
int newY = p.second + dirs[i][1];
if (isSafe(newX, newY) && dist[newX][newY] > dist[p.first][p.second] + 1 && visited(newX, newY)) {
zeroes.push({newX, newY});
dist[newX][newY] = dist[p.first][p.second] + 1;
}
}
};

while (!zeroes.empty()) {
pair<int, int> p = zeroes.front();
zeroes.pop();

addAdjacent(p);
}

return dist;
}
};
58 changes: 58 additions & 0 deletions floodFill.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
queue<pair<int, int>> q;
unordered_set<string> visited;
int original = image[sr][sc];

q.push({sr, sc});

auto getKey = [&](int x, int y){
return to_string(x) + "," + to_string(y);
};

visited.insert(getKey(sr, sc));


auto isSafe = [&](int x, int y) -> bool {
if (x >= 0 && y >=0 && x < image.size() && y < image[0].size()) {
return true;
}
return false;
};

auto isVisited = [&](pair<int, int> cell) -> bool {
string key = getKey(cell.first, cell.second);

if (visited.find(key) == visited.end()) {
visited.insert(key);
} else {
return false;
}
return true;
};

auto addAdjacentCells = [&](pair<int, int> cell) -> void {
vector<vector<int>> dirs = {{0,1}, {0,-1}, {1, 0}, {-1,0}};
for (int i=0;i<dirs.size();i++) {
int newX = cell.first + dirs[i][0];
int newY = cell.second + dirs[i][1];
if (isSafe(newX, newY) && isVisited({newX, newY})) {
q.push({newX, newY});
}
}
};

while (!q.empty()) {
auto cell = q.front();
q.pop();

if (image[cell.first][cell.second] == original) {
image[cell.first][cell.second] = color;
addAdjacentCells(cell);
}
}

return image;
}
};