Skip to content

Commit fd00de6

Browse files
authored
Improved tasks 48-72
1 parent d40109d commit fd00de6

File tree

10 files changed

+450
-388
lines changed

10 files changed

+450
-388
lines changed

src/main/python/g0001_0100/s0048_rotate_image/readme.md

Lines changed: 61 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -41,48 +41,66 @@ You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-pla
4141
* `1 <= n <= 20`
4242
* `-1000 <= matrix[i][j] <= 1000`
4343

44-
To solve the "Rotate Image" problem in Java with a `Solution` class, we can follow these steps:
45-
46-
1. Define a `Solution` class.
47-
2. Define a method named `rotate` that takes a 2D array `matrix` representing an image as input and rotates the image by 90 degrees clockwise.
48-
3. Determine the number of layers in the matrix, which is equal to half of the matrix's size.
49-
4. Iterate through each layer from outer to inner layers.
50-
5. For each layer:
51-
- Iterate through each element in the current layer.
52-
- Swap the elements of the current layer in a clockwise manner.
53-
6. Return the rotated matrix.
54-
55-
Here's the implementation:
56-
57-
```java
58-
public class Solution {
59-
public void rotate(int[][] matrix) {
60-
int n = matrix.length;
61-
int layers = n / 2;
62-
63-
for (int layer = 0; layer < layers; layer++) {
64-
int first = layer;
65-
int last = n - 1 - layer;
66-
67-
for (int i = first; i < last; i++) {
68-
int offset = i - first;
69-
int top = matrix[first][i];
70-
71-
// Move left to top
72-
matrix[first][i] = matrix[last - offset][first];
73-
74-
// Move bottom to left
75-
matrix[last - offset][first] = matrix[last][last - offset];
76-
77-
// Move right to bottom
78-
matrix[last][last - offset] = matrix[i][last];
79-
80-
// Move top to right
81-
matrix[i][last] = top;
82-
}
83-
}
84-
}
85-
}
44+
To solve the "Rotate Image" problem, you can perform the rotation in-place by swapping elements of the matrix. Here are the steps to solve the problem:
45+
46+
### Approach:
47+
48+
1. **Transpose the Matrix:**
49+
- Transpose the matrix by swapping `matrix[i][j]` with `matrix[j][i]` for all `i` and `j` where `i < j`.
50+
51+
2. **Reverse Each Row:**
52+
- Reverse each row of the transposed matrix to get the final rotated matrix.
53+
54+
### Python Code:
55+
56+
```python
57+
class Solution:
58+
def rotate(self, matrix):
59+
n = len(matrix)
60+
61+
# Transpose the matrix
62+
for i in range(n):
63+
for j in range(i + 1, n):
64+
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
65+
66+
# Reverse each row
67+
for i in range(n):
68+
matrix[i] = matrix[i][::-1]
69+
70+
# Example Usage:
71+
solution = Solution()
72+
73+
# Example 1:
74+
matrix1 = [
75+
[1,2,3],
76+
[4,5,6],
77+
[7,8,9]
78+
]
79+
solution.rotate(matrix1)
80+
print(matrix1) # Output: [[7,4,1],[8,5,2],[9,6,3]]
81+
82+
# Example 2:
83+
matrix2 = [
84+
[5,1,9,11],
85+
[2,4,8,10],
86+
[13,3,6,7],
87+
[15,14,12,16]
88+
]
89+
solution.rotate(matrix2)
90+
print(matrix2) # Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
91+
92+
# Example 3:
93+
matrix3 = [[1]]
94+
solution.rotate(matrix3)
95+
print(matrix3) # Output: [[1]]
96+
97+
# Example 4:
98+
matrix4 = [
99+
[1,2],
100+
[3,4]
101+
]
102+
solution.rotate(matrix4)
103+
print(matrix4) # Output: [[3,1],[4,2]]
86104
```
87105

88-
This implementation provides a solution to the "Rotate Image" problem in Java. It rotates the given 2D matrix representing an image by 90 degrees clockwise in-place.
106+
This code defines a `Solution` class with a `rotate` method to rotate the given matrix by 90 degrees clockwise. The example usage demonstrates how to create an instance of the `Solution` class and call the `rotate` method with different input matrices.

src/main/python/g0001_0100/s0049_group_anagrams/readme.md

Lines changed: 50 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -30,50 +30,57 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ
3030
* `0 <= strs[i].length <= 100`
3131
* `strs[i]` consists of lowercase English letters.
3232

33-
To solve the "Group Anagrams" problem in Java with the Solution class, follow these steps:
34-
35-
1. Define a method `groupAnagrams` in the `Solution` class that takes an array of strings `strs` as input and returns a list of lists of strings.
36-
2. Initialize an empty HashMap to store the groups of anagrams. The key will be the sorted string, and the value will be a list of strings.
37-
3. Iterate through each string `str` in the input array `strs`.
38-
4. Sort the characters of the current string `str` to create a key for the HashMap.
39-
5. Check if the sorted string exists as a key in the HashMap:
40-
- If it does, add the original string `str` to the corresponding list of strings.
41-
- If it doesn't, create a new entry in the HashMap with the sorted string as the key and a new list containing `str` as the value.
42-
6. After iterating through all strings, return the values of the HashMap as the result.
43-
44-
Here's the implementation of the `groupAnagrams` method in Java:
45-
46-
```java
47-
import java.util.*;
48-
49-
class Solution {
50-
public List<List<String>> groupAnagrams(String[] strs) {
51-
// Initialize a HashMap to store the groups of anagrams
52-
Map<String, List<String>> anagramGroups = new HashMap<>();
33+
To solve the "Group Anagrams" problem, you can use a hash table to group the anagrams together based on their sorted representations. Here are the steps to solve the problem:
34+
35+
### Approach:
36+
37+
1. **Initialize a Hash Table:**
38+
- Initialize an empty dictionary to store the groups of anagrams. The keys of the dictionary will be the sorted representations of the words, and the values will be lists containing the original words.
39+
40+
2. **Iterate Through the Strings:**
41+
- Iterate through each string in the given array `strs`.
42+
43+
3. **Sort Each String:**
44+
- For each string, sort its characters alphabetically to get its sorted representation.
45+
46+
4. **Group Anagrams:**
47+
- Use the sorted representation as the key in the dictionary and append the original word to the corresponding list in the dictionary.
48+
49+
5. **Return the Groups:**
50+
- Return the values of the dictionary, which contain the groups of anagrams.
51+
52+
### Python Code:
53+
54+
```python
55+
from collections import defaultdict
56+
57+
class Solution:
58+
def groupAnagrams(self, strs):
59+
# Initialize a dictionary to store groups of anagrams
60+
groups = defaultdict(list)
5361

54-
// Iterate through each string in the input array
55-
for (String str : strs) {
56-
// Sort the characters of the current string
57-
char[] chars = str.toCharArray();
58-
Arrays.sort(chars);
59-
String sortedStr = new String(chars);
60-
61-
// Check if the sorted string exists as a key in the HashMap
62-
if (anagramGroups.containsKey(sortedStr)) {
63-
// If it does, add the original string to the corresponding list
64-
anagramGroups.get(sortedStr).add(str);
65-
} else {
66-
// If it doesn't, create a new entry in the HashMap
67-
List<String> group = new ArrayList<>();
68-
group.add(str);
69-
anagramGroups.put(sortedStr, group);
70-
}
71-
}
62+
# Group anagrams based on their sorted representations
63+
for word in strs:
64+
sorted_word = ''.join(sorted(word))
65+
groups[sorted_word].append(word)
7266

73-
// Return the values of the HashMap as the result
74-
return new ArrayList<>(anagramGroups.values());
75-
}
76-
}
67+
# Return the groups of anagrams
68+
return list(groups.values())
69+
70+
# Example Usage:
71+
solution = Solution()
72+
73+
# Example 1:
74+
strs1 = ["eat","tea","tan","ate","nat","bat"]
75+
print(solution.groupAnagrams(strs1)) # Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
76+
77+
# Example 2:
78+
strs2 = [""]
79+
print(solution.groupAnagrams(strs2)) # Output: [[""]]
80+
81+
# Example 3:
82+
strs3 = ["a"]
83+
print(solution.groupAnagrams(strs3)) # Output: [["a"]]
7784
```
7885

79-
This implementation ensures that all anagrams are grouped together efficiently using a HashMap.
86+
This code defines a `Solution` class with a `groupAnagrams` method to group the anagrams together. The example usage demonstrates how to create an instance of the `Solution` class and call the `groupAnagrams` method with different input arrays of strings.

src/main/python/g0001_0100/s0051_n_queens/readme.md

Lines changed: 67 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -28,81 +28,72 @@ Each solution contains a distinct board configuration of the n-queens' placement
2828

2929
* `1 <= n <= 9`
3030

31-
To solve the "N-Queens" problem in Java with the Solution class, follow these steps:
32-
33-
1. Define a method `solveNQueens` in the `Solution` class that takes an integer `n` as input and returns a list of lists of strings.
34-
2. Initialize a board represented as a 2D character array of size `n x n`. Initialize all cells to `'.'`, indicating an empty space.
35-
3. Define a recursive backtracking function `backtrack` to explore all possible configurations of queens on the board.
36-
4. In the `backtrack` function:
37-
- Base case: If the current row index `row` is equal to `n`, it means we have successfully placed `n` queens on the board. Add the current board configuration to the result.
38-
- Iterate through each column index `col` from `0` to `n - 1`:
39-
- Check if it's safe to place a queen at position `(row, col)` by calling a helper function `isSafe`.
40-
- If it's safe, place a queen at position `(row, col)` on the board, mark it as `'Q'`.
41-
- Recur to the next row by calling `backtrack(row + 1)`.
42-
- Backtrack: After exploring all possibilities, remove the queen from position `(row, col)` by marking it as `'.'`.
43-
5. In the `solveNQueens` method, initialize an empty list `result` to store the solutions.
44-
6. Call the `backtrack` function with initial parameters `0` for the row index.
45-
7. Return the `result` list containing all distinct solutions.
46-
47-
Here's the implementation of the `solveNQueens` method in Java:
48-
49-
```java
50-
import java.util.*;
51-
52-
class Solution {
53-
public List<List<String>> solveNQueens(int n) {
54-
List<List<String>> result = new ArrayList<>();
55-
char[][] board = new char[n][n];
56-
for (int i = 0; i < n; i++) {
57-
Arrays.fill(board[i], '.');
58-
}
59-
backtrack(board, 0, result);
60-
return result;
61-
}
62-
63-
private void backtrack(char[][] board, int row, List<List<String>> result) {
64-
int n = board.length;
65-
if (row == n) {
66-
result.add(constructBoard(board));
67-
return;
68-
}
69-
for (int col = 0; col < n; col++) {
70-
if (isSafe(board, row, col)) {
71-
board[row][col] = 'Q';
72-
backtrack(board, row + 1, result);
73-
board[row][col] = '.';
74-
}
75-
}
76-
}
77-
78-
private boolean isSafe(char[][] board, int row, int col) {
79-
int n = board.length;
80-
for (int i = 0; i < row; i++) {
81-
if (board[i][col] == 'Q') {
82-
return false;
83-
}
84-
}
85-
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
86-
if (board[i][j] == 'Q') {
87-
return false;
88-
}
89-
}
90-
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
91-
if (board[i][j] == 'Q') {
92-
return false;
93-
}
94-
}
95-
return true;
96-
}
97-
98-
private List<String> constructBoard(char[][] board) {
99-
List<String> solution = new ArrayList<>();
100-
for (char[] row : board) {
101-
solution.add(new String(row));
102-
}
103-
return solution;
104-
}
105-
}
31+
To solve the N-Queens problem, which involves placing N queens on an N x N chessboard without attacking each other, you can use backtracking. Here are the steps to solve the problem:
32+
33+
### Approach:
34+
35+
1. **Initialize the Chessboard:**
36+
- Initialize an empty N x N chessboard grid.
37+
38+
2. **Backtracking Function:**
39+
- Define a backtracking function to recursively explore all possible queen placements.
40+
41+
3. **Base Case:**
42+
- If all queens are placed (i.e., row index equals N), add the current configuration to the list of solutions.
43+
44+
4. **Try Placing Queen:**
45+
- For the current row, try placing the queen in each column (0 to N-1).
46+
- If placing the queen at the current position is safe (i.e., not attacking any other queen), mark the cell as a queen ('Q') and recursively move to the next row.
47+
48+
5. **Backtrack:**
49+
- After exploring all possibilities from the current position, backtrack by removing the queen from the current position and try the next column.
50+
51+
6. **Return Solutions:**
52+
- Return the list of all distinct solutions found.
53+
54+
### Python Code:
55+
56+
```python
57+
class Solution:
58+
def solveNQueens(self, n):
59+
def is_safe(row, col):
60+
# Check for queens in the same column
61+
for i in range(row):
62+
if board[i][col] == 'Q':
63+
return False
64+
65+
# Check for queens in the upper-left diagonal
66+
for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)):
67+
if board[i][j] == 'Q':
68+
return False
69+
70+
# Check for queens in the upper-right diagonal
71+
for i, j in zip(range(row-1, -1, -1), range(col+1, n)):
72+
if board[i][j] == 'Q':
73+
return False
74+
75+
return True
76+
77+
def backtrack(row):
78+
if row == n:
79+
solutions.append([''.join(row) for row in board])
80+
return
81+
82+
for col in range(n):
83+
if is_safe(row, col):
84+
board[row][col] = 'Q'
85+
backtrack(row + 1)
86+
board[row][col] = '.'
87+
88+
board = [['.' for _ in range(n)] for _ in range(n)]
89+
solutions = []
90+
backtrack(0)
91+
return solutions
92+
93+
# Example Usage:
94+
solution = Solution()
95+
print(solution.solveNQueens(4)) # Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
96+
print(solution.solveNQueens(1)) # Output: [["Q"]]
10697
```
10798

108-
This implementation efficiently finds all distinct solutions to the N-Queens problem using backtracking.
99+
This code defines a `Solution` class with a `solveNQueens` method to find all distinct solutions to the N-Queens puzzle. The example usage demonstrates how to create an instance of the `Solution` class and call the `solveNQueens` method with different values of `n`.

0 commit comments

Comments
 (0)