diff --git a/01-matrix.cpp b/01-matrix.cpp new file mode 100644 index 00000000..e6eeba22 --- /dev/null +++ b/01-matrix.cpp @@ -0,0 +1,61 @@ +class Solution { +public: + vector> updateMatrix(vector>& mat) { + queue> zeroes; + int n = mat.size(); + int m = mat[0].size(); + + vector> dist(n, vector(m,INT_MAX)); + unordered_set us; + + for (int i=0;i 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 p) -> void { + vector> dirs = {{1,0}, {-1,0} ,{0, 1} , {0, -1}}; + for (int i=0;i 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 p = zeroes.front(); + zeroes.pop(); + + addAdjacent(p); + } + + return dist; + } +}; diff --git a/floodFill.cpp b/floodFill.cpp new file mode 100644 index 00000000..dab18a83 --- /dev/null +++ b/floodFill.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int color) { + queue> q; + unordered_set 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 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 cell) -> void { + vector> dirs = {{0,1}, {0,-1}, {1, 0}, {-1,0}}; + for (int i=0;i