You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
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
+
classSolution:
58
+
defgroupAnagrams(self, strs):
59
+
# Initialize a dictionary to store groups of anagrams
60
+
groups = defaultdict(list)
53
61
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 =newString(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 =newArrayList<>();
68
-
group.add(str);
69
-
anagramGroups.put(sortedStr, group);
70
-
}
71
-
}
62
+
# Group anagrams based on their sorted representations
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.
Copy file name to clipboardExpand all lines: src/main/python/g0001_0100/s0051_n_queens/readme.md
+67-76Lines changed: 67 additions & 76 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -28,81 +28,72 @@ Each solution contains a distinct board configuration of the n-queens' placement
28
28
29
29
*`1 <= n <= 9`
30
30
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:
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
+
classSolution:
58
+
defsolveNQueens(self, n):
59
+
defis_safe(row, col):
60
+
# Check for queens in the same column
61
+
for i inrange(row):
62
+
if board[i][col] =='Q':
63
+
returnFalse
64
+
65
+
# Check for queens in the upper-left diagonal
66
+
for i, j inzip(range(row-1, -1, -1), range(col-1, -1, -1)):
67
+
if board[i][j] =='Q':
68
+
returnFalse
69
+
70
+
# Check for queens in the upper-right diagonal
71
+
for i, j inzip(range(row-1, -1, -1), range(col+1, n)):
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