LeetCode Daily: Build a Matrix With Conditions Solution in Java | July 21, 2024 #leetcodechallenge

preview_player
Показать описание
🔍 **LeetCode Problem of the Day**: Build a Matrix With Conditions

Welcome to today's LeetCode challenge! In this video, I will show you how to solve the problem "Build a Matrix With Conditions" in Java. This problem involves constructing a matrix based on given conditions using graph theory and topological sorting.

👉 **Solution**: Pinned on the comments

### 🌟 Problem Description:
The problem "Build a Matrix With Conditions" requires you to construct a matrix that satisfies certain conditions using graph theory principles and topological sorting. This problem is great for practicing advanced algorithm techniques in Java.

### 🔑 Key Points:
1. Understand the problem requirements and constraints.
2. Use graph theory and topological sort to construct the matrix.
3. Implement the solution in Java.

### 📅 **Daily Solutions**:
I will be posting solutions to the LeetCode daily problems every day. Make sure to subscribe and hit the bell icon to stay updated!

### 👥 **Join the Community**:
- Share your solutions in the comments.
- Connect with fellow coders and enhance your problem-solving skills.

If you enjoyed this video, don't forget to like, share, and subscribe for more daily LeetCode solutions!

#LeetCode #Coding #Programming #TechInterview #GraphTheory #TopologicalSort #Algorithm #DailyChallenge #Java #YouTubeShorts
Рекомендации по теме
Комментарии
Автор

class Solution {

public int[] kahnAlgo(int[][] conditions, int k) {
int[] indegree = new int[k + 1];
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int i = 0; i <= k; i++) {
adjacencyList.add(new ArrayList<>());
}
for (int[] condition : conditions) {
int from = condition[0];
int to = condition[1];
indegree[to]++;

}

Queue<Integer> q = new LinkedList<>();
for (int i = 1; i <= k; i++) {
if (indegree[i] == 0) {
q.offer(i);
}
}

int[] arr = new int[k];
int idx = 0;
while (!q.isEmpty()) {
int currentValue = q.poll();
arr[idx++] = currentValue;
for (int neighbor : {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
q.offer(neighbor);
}
}
}

if (idx != k) {
return new int[0];
}

return arr;
}

public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
int[] row = kahnAlgo(rowConditions, k);
int[] col = kahnAlgo(colConditions, k);

if (row.length == 0 || col.length == 0) {
return new int[0][0];
}

int[][] res = new int[k][k];
Map<Integer, Integer> rowPosition = new HashMap<>();
Map<Integer, Integer> colPosition = new HashMap<>();

for (int i = 0; i < k; i++) {
rowPosition.put(row[i], i);
colPosition.put(col[i], i);
}

for (int i = 1; i <= k; i++) {
int r = rowPosition.get(i);
int c = colPosition.get(i);
res[r][c] = i;
}

return res;
}
}

AlgoXploration