boolisArea(vector<vector<char>>& grid, int row, int col){ int m = grid.size(); int n = grid[0].size(); if(row >= 0 && row < m && col >= 0 && col < n){ returntrue; } returnfalse; } };
boolisArea(vector<vector<char>>& grid, int row, int col){ int m = grid.size(); int n = grid[0].size(); if(row >= 0 && row < m && col >= 0 && col < n){ returntrue; } returnfalse; } };
classSolution { public: intnumIslands(vector<vector<char>>& grid){ int m = grid.size(); int n = grid[0].size(); UnionFind uf(grid);
for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == '1'){ grid[i][j] = '2'; // 向上下左右四个方向扩展 int x = i * n + j; if(isIsland(grid, i-1, j)){ uf.unite(x, (i-1) * n + j); } if(isIsland(grid, i+1, j)){ uf.unite(x, (i+1) * n + j); } if(isIsland(grid, i, j-1)){ uf.unite(x, i * n + (j-1)); } if(isIsland(grid, i, j+1)){ uf.unite(x, i * n + (j+1)); } } } }
return uf.getCount(); }
boolisIsland(vector<vector<char>>& grid, int row, int col){ int m = grid.size(); int n = grid[0].size(); if(row >= 0 && row < m && col >= 0 && col < n && grid[row][col] == '1'){ returntrue; } returnfalse; } };
classSolution { public: intorangesRotting(vector<vector<int>>& grid){ int m = grid.size(); int n = grid[0].size(); queue<pair<int, int>> que; // 用于存储腐烂橘子的位置 int freshCount = 0; // 新鲜橘子数量
// 初始化队列并统计新鲜橘子 for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 2){ que.push({i, j}); }elseif(grid[i][j] == 1){ freshCount++; } } }
// 如果没有新鲜橘子,直接返回 0 if (freshCount == 0) return0;
// 四个方向 vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int time = 0;
// BFS 开始传播腐烂 while (!que.empty()){ int size = que.size(); bool spread = false; // 本轮是否有扩展 while(size--){ auto rc = que.front(); que.pop();
int x = rc.first, y = rc.second; for(auto dir : directions){ int i = x + dir.first, j = y + dir.second; if(i >= 0 && i < m && j >= 0 && j < n && grid[i][j] == 1){ freshCount--; grid[i][j] = 2; que.push({i, j}); spread = true; } } } if(spread){ time++; } }
intfind(string word){ Node* cur = root; for(char c : word){ if(cur->son[c-'a'] == nullptr){ return0; } cur = cur->son[c-'a']; } return cur->end ? 2 : 1; // 如果整个单词到叶子节点则返回2,否则返回1 } };
/** * 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); */
时间复杂度:初始化为 O(1),insert 为 O(n∣Σ∣),其余为 O(n),其中 n 是 word 的长度,∣Σ∣=26 是字符集合的大小。注意创建一个节点需要 O(∣Σ∣) 的时间(如果用的是数组)。