Algorithms in Java
Posted on Feb 26, 2025 in Computer Engineering
Trapping Rain Water | Unique Paths II | Word Ladder |
---|
public int trap(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int n = height.length;
int left = 0, right = n - 1;
int leftMax = 0, rightMax = 0;
int waterTrapped = 0;
while (left <= right) {
if (height[left] <= height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
waterTrapped += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
waterTrapped += rightMax - height[right];
}
right--;
}
}
return waterTrapped;
}
| public class UniquePathsII {
public int uniquePathsWithObstacles(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
// If the starting cell has an obstacle, return 0
if (grid[0][0] == 1) {
return 0;
}
// Initialize the starting point
grid[0][0] = 1;
// Fill the first column
for (int i = 1; i < m; i++) {
grid[i][0] = (grid[i][0] == 0 && grid[i-1][0] == 1) ? 1 : 0;
}
// Fill the first row
for (int j = 1; j < n; j++) {
grid[0][j] = (grid[0][j] == 0 && grid[0][j-1] == 1) ? 1 : 0;
}
// Fill the rest of the grid
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (grid[i][j] == 0) {
grid[i][j] = grid[i-1][j] + grid[i][j-1];
} else {
grid[i][j] = 0;
}
}
}
// Return the value at the bottom-right corner
return grid[m-1][n-1];
}
}
| class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord))
return 0;
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
int level = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String currentWord = queue.poll();
for (int j = 0; j < currentWord.length(); j++) {
char[] wordChars = currentWord.toCharArray();
for (char c = 'a'; c <= 'z'; c++) {
wordChars[j] = c;
String nextWord = new String(wordChars);
if (nextWord.equals(endWord)) {
return level + 1;
}
if (words.contains(nextWord)) {
queue.offer(nextWord);
words.remove(nextWord);
}
}
}
}
level++;
}
return 0;
}
}
|