Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create: 0127-word-ladder.dart #3476

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
48 changes: 48 additions & 0 deletions dart/0127-word-ladder.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
List<int> findRedundantConnection(List<List<int>> edges) {
List<int> parent = [];
for (int i = 0; i < edges.length + 1; i++) {
parent.add(i);
}

List<int> sizes = List.filled(edges.length + 1, 1);

int find(int n) {
int p = parent[n];

while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}

return p;
}

bool union(int node1, int node2) {
int parentOf1 = find(node1);
int parentOf2 = find(node2);

if (parentOf1 == parentOf2) {
return false;
} else if (sizes[parentOf1] > sizes[parentOf2]) {
parent[parentOf2] = parentOf1;
sizes[parentOf1] += sizes[parentOf2];
} else {
parent[parentOf1] = parentOf2;
sizes[parentOf2] += sizes[parentOf1];
}

return true;
}

for (List<int> edge in edges) {
int node1 = edge[0];
int node2 = edge[1];
if (!union(node1, node2)) {
return [node1, node2];
}
}

return [];
}
}
51 changes: 51 additions & 0 deletions dart/0130-surrounded-regions.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution {
late List<List<String>> board;
late int rows;
late int columns;

bool isInBound(int row, int column) {
return 0 <= row && row < rows && 0 <= column && column < columns;
}

void dfs(int row, int column) {
if (!isInBound(row, column) || board[row][column] != 'O') {
return;
}

board[row][column] = 'T';

dfs(row + 1, column);
dfs(row, column + 1);
dfs(row - 1, column);
dfs(row, column - 1);
}

void solve(List<List<String>> board) {
this.board = board;
rows = board.length;
columns = board[0].length;

// Traverse the first and last columns
for (int column = 0; column < columns; column++) {
dfs(0, column);
dfs(rows - 1, column);
}

// Traverse the first and last rows
for (int row = 0; row < rows; row++) {
dfs(row, 0);
dfs(row, columns - 1);
}

// Replace all 'O' with 'X' and 'T' back to 'O'
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
if (board[row][column] == 'O') {
board[row][column] = 'X';
} else if (board[row][column] == 'T') {
board[row][column] = 'O';
}
}
}
}
}