voiddfs(vector<vector<char>> &grid, int start_i, int start_j) { if (start_i < 0 || start_i >= grid.size() || start_j < 0 || start_j >= grid[0].size()) return; if (grid[start_i][start_j] == '0') return; grid[start_i][start_j] = '0';
for (int k = 0; k < 4; k ++) { int x = k < 2 ? (k % 2 ? 1 : -1) : 0; int y = k < 2 ? 0 : (k % 2 ? 1 : -1);
dfs(grid, start_i + x, start_j + y); } }
intnumIslands(vector<vector<char>>& grid){
int m = grid.size(); int n = grid[0].size(); int ans = 0; for (int i = 0; i < m; i ++) { for (int j = 0; j < n; j ++) { if (grid[i][j] == '1') { dfs(grid, i, j); ans ++; } } } return ans; } };
intorangesRotting(vector<vector<int>>& grid){ int m = grid.size(); int n = grid[0].size();
queue<int> bad_queue;
int good_count = 0; for (int i = 0; i < m; i ++) { for (int j = 0; j < n; j ++) { if (grid[i][j] == 2) { bad_queue.push((i * n + j)); } elseif (grid[i][j] == 1) { good_count ++; } } } if (good_count == 0) return0;
if (bad_queue.empty()) return-1; int ans = 0;
while (!bad_queue.empty()) { int size = bad_queue.size(); bool flag = false; for (int c = 0; c < size; c ++) { int idx = bad_queue.front(); bad_queue.pop();
int i = idx / n, j = idx % n;
for (int x = 0; x < 4; x ++) { int di = i + (x < 2 ? (x % 2 ? -1 : 1) : 0); int dj = j + (x < 2 ? 0 : (x % 2 ? -1 : 1));
if (di >= 0 && di < m && dj >= 0 && dj < n) { if (grid[di][dj] == 1) { grid[di][dj] = 2; bad_queue.push((di * n + dj)); flag = true; good_count --; } } } } if (flag) ans ++; }
voidinsert(string word){ Trie *pre = this; for (char c : word) { if (pre->children[c-'a'] == nullptr) pre->children[c-'a'] = newTrie(); pre = pre->children[c-'a']; } pre->is_end = true; }
boolsearch(string word){ Trie *pre = this; for (char c : word) { if (pre->children[c-'a'] == nullptr) returnfalse; pre = pre->children[c-'a']; } return pre->is_end; }
boolstartsWith(string prefix){ Trie *pre = this; for (char c : prefix) { if (pre->children[c-'a'] == nullptr) returnfalse; pre = pre->children[c-'a']; } returntrue; } };
/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */