Skip to content

Commit c452e4c

Browse files
committed
Update matrix algorithms
1 parent e1c2005 commit c452e4c

39 files changed

+813
-144
lines changed

README.md

+11-9
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@ List of Programs related to data structures and algorithms
44
## Data Structures
55

66
### Stack
7-
1. Stack using array: [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/stack_with_array.js)
87

9-
2. Stack using linkedlist: [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/stack_with_linkedlist.js)
8+
| No. | Name | Source | Live | Documentation | Level | Pattern |
9+
| :-: | :---------------- | :---------------------------------------------------------------------------------------------------------------------------------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------: | :---: | :--------------------: |
10+
| 1 | Stack using array | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/1.stack_with_array/stack_with_array.js) | [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/1.stack_with_array//stack_with_array.js) | -<!--[Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/1.stack_with_array//stack_with_array.md) --> | Easy | Using Array operations |
11+
| 2 | Stack using linkedlist | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/2.stack_with_linkedlist/stack_with_linkedlist.js) | [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/2.stack_with_linkedlist/stack_with_linkedlist.js) | -<!--[Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/stack/2.stack_with_linkedlist/stack_with_linkedlist.md) --> | Easy | Using LinkedList operations |
12+
1013

1114
### Queue
1215
1. Queue using array: [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/datastructures/queue/queue_array.js)
@@ -166,14 +169,13 @@ List of Programs related to data structures and algorithms
166169
| 7 | Number of connected components in an undirected graph | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/graph/7.numberOfConnectedComponents/numberOfConnectedComponents.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/graph/7.numberOfConnectedComponents/numberOfConnectedComponents.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/graph/7.numberOfConnectedComponents/numberOfConnectedComponents.md) | Medium | Union Find algorithm(+ union by rank & path compression) |
167170

168171
### Matrix
172+
| No. | Name | Source | Live | Documentation | Level | Pattern |
173+
| :-: | :--------------- | :-----------------------------------------------------------------------------------------------------------------------------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----: | :--------------------------------: |
174+
| 1 | Set matrix zeros | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/1.setMatrixZeroes/setMatrixZeroes.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/1.setMatrixZeroes/setMatrixZeroes.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/1.setMatrixZeroes/setMatrixZeroes.md) | Medium | In-place updates through traversal |
175+
| 2. | Spiral matrix | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/2.spiralMatrix/spiralMatrix.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/2.spiralMatrix/spiralMatrix.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/2.spiralMatrix/spiralMatrix.md) | Medium | Boundary matrix traversal/spiral pattern |
176+
| 3 | Rotate image | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/3.rotateImage/rotateImage.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/3.rotateImage/rotateImage.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/3.rotateImage/rotateImage.md) | Medium | Inplace square rotation |
177+
| 4 | Word search | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/4.wordSearch/wordSearch.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/4.wordSearch/wordSearch.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/4.wordSearch/wordSearch.md) | Medium | Depth-First Search (DFS) using recursion |
169178

170-
1. Set matrix zeros: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/setMatrixZeros.js)
171-
172-
2. Spiral matrix: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/spiralMatrix.js)
173-
174-
3. Rotate image: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/rotateImage.js)
175-
176-
4. Word search: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/matrix/wordSearch.js)
177179

178180
### Interval
179181

src/images/rotate-image1.png

5.6 KB
Loading

src/images/rotate-image2.png

10.4 KB
Loading

src/images/rotate-image3.png

14 KB
Loading

src/images/rotate-image4.png

21.3 KB
Loading

src/images/set-matrix-zeros1.png

9.93 KB
Loading

src/images/set-matrix-zeros2.png

11.5 KB
Loading

src/images/spiral-matrix1.png

4.89 KB
Loading

src/images/spiral-matrix2.png

9.23 KB
Loading

src/images/spiral-matrix3.png

12 KB
Loading

src/images/spiral-solution.png

17.8 KB
Loading

src/images/word-search1.png

6.89 KB
Loading

src/images/word-search2.png

9.18 KB
Loading

src/java1/algorithms/matrix/SpiralMatrix.java

-48
This file was deleted.

src/java1/algorithms/matrix/RotateImage.java src/java1/algorithms/matrix/rotateImage/RotateImage.java

+18-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
package java1.algorithms.matrix;
1+
package java1.algorithms.matrix.rotateImage;
22

33
import java.util.Arrays;
44

55
public class RotateImage {
6-
// TC: O(n*2) SC: O(1)
6+
// TC: O(n^2) SC: O(1)
77
private static void rotate(int[][] matrix) {
88
int left =0, right = matrix[0].length-1;
99

@@ -32,13 +32,26 @@ private static void rotate(int[][] matrix) {
3232
}
3333

3434
public static void main(String[] args) {
35-
int[][] matrix = {
35+
int[][] matrix1 = {
36+
{1, 2},
37+
{3, 4}
38+
};
39+
int[][] matrix2 = {
40+
{1,2,3},
41+
{4,5,6},
42+
{7,8,9}
43+
};
44+
int[][] matrix3 = {
3645
{1, 2, 3, 4},
3746
{5, 6, 7, 8},
3847
{9, 10, 11, 12},
3948
{13, 14, 15, 16}
4049
};
41-
rotate(matrix);
42-
System.out.println(Arrays.deepToString(matrix));
50+
rotate(matrix1);
51+
rotate(matrix2);
52+
rotate(matrix3);
53+
System.out.println(Arrays.deepToString(matrix1));
54+
System.out.println(Arrays.deepToString(matrix2));
55+
System.out.println(Arrays.deepToString(matrix3));
4356
}
4457
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
**Problem statement:**
2+
Given an `n x n` square matrix of integers `matrix`, rotate it by 90 degrees clockwise.
3+
4+
**Note:** You must rotate the matrix in-place without allocating another 2D matrix to do the rotation.
5+
6+
## Examples:
7+
Example1:
8+
9+
Input: matrix = [
10+
[1,2],
11+
[3,4]
12+
]
13+
14+
Output: [
15+
[3, 1],
16+
[4, 2]
17+
]
18+
19+
20+
![Screenshot](../../../../images/rotate-image1.png)
21+
22+
Example2:
23+
24+
Input: matrix = [
25+
[1,2,3],
26+
[4,5,6],
27+
[7,8,9]
28+
]
29+
30+
Output: [
31+
[7,4,1],
32+
[8,5,2],
33+
[9,6,3]
34+
]
35+
36+
![Screenshot](../../../../images/rotate-image2.png)
37+
38+
Example3:
39+
40+
Input: matrix = [
41+
[1,2,3],
42+
[4,5,6],
43+
[7,8,9]
44+
]
45+
46+
Output: [
47+
[1, 2, 3, 4],
48+
[5, 6, 7, 8],
49+
[9, 10, 11, 12],
50+
[13, 14, 15, 16]
51+
]
52+
53+
![Screenshot](../../../../images/rotate-image3.png)
54+
55+
56+
**Algorithmic Steps**
57+
This problem is solved by inplace square rotation technique in which corner cells of a square rotated by 90 degress in a clockwise direction. Moreover, the rotation starts from bottom left cell and one extra variable is used to store the previous value of top left cell value. The algorithmic approach can be summarized as follows:
58+
59+
![Screenshot](../../../../images/rotate-image4.png)
60+
61+
1. Create a function(`rotateImage`) by accepting the `n*n` matrix as input parameter.
62+
63+
2. Define two pointers `left` and `right` point to first and last column indexes. They are helpful to traverse over the cells.
64+
65+
3. Traverse over each cell until left pointer is less than equals to right pointer.
66+
67+
1. Add a nested loop `n-1`(i.e, `right-left`) times to update the cell values by 90 degrees.
68+
1. Store the top left cell's value in a temporary variable(`topLeft`) before it is going to updated.
69+
2. Move bottom left value to top left cell's position.
70+
3. Move bottom right value to bottom left cell's position.
71+
4. Move top right value to bottom right cell's position.
72+
5. Copy top left temporary variable to top right cell's position.
73+
74+
2. Increment left pointer by 1 and decrement right pointer by 1 upon completion of one full rotation.
75+
76+
4. Repeat the rotation until all the cells rotated by 90 degrees. i.e, left pointer is less than right pointer.
77+
78+
79+
**Time and Space complexity:**
80+
This algorithm has a time complexity of `O(n^2))`, where `n` is the number of rows or the number of columns in the given matrix. This is because each element needs to moved exactly once.
81+
82+
It requires `O(1)` constant space complexity irrespective of the matrix size. This is becuase we don't need to use any additional temporary space(except a pointer variable) considering inplace matrix update.

src/java1/algorithms/matrix/SetMatrixZeros.java src/java1/algorithms/matrix/setMatrixZeroes/SetMatrixZeroes.java

+12-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
package java1.algorithms.matrix;
1+
package java1.algorithms.matrix.setMatrixZeroes;
22
import java.util.*;
33

4-
public class SetMatrixZeros {
5-
//TC: O(rows*cols) SC:O(1)
4+
public class SetMatrixZeroes {
5+
//TC: O(m*n) SC:O(1)
66
private static void setZeros(int[][] matrix) {
77
int rows = matrix.length, cols = matrix[0].length;
88
boolean rowZero = false;
@@ -30,7 +30,7 @@ private static void setZeros(int[][] matrix) {
3030
}
3131

3232
if(matrix[0][0] == 0) {
33-
for(int r=0; r<rows; r++) {
33+
for(int r=1; r<rows; r++) {
3434
matrix[r][0] = 0;
3535
}
3636
}
@@ -44,10 +44,15 @@ private static void setZeros(int[][] matrix) {
4444
}
4545

4646
public static void main(String[] args) {
47-
int[][] matrix = {
47+
int[][] matrix1 = {
4848
{1, 0, 1}, {1, 0, 1}, {0, 1, 1}
4949
};
50-
setZeros(matrix);
51-
System.out.println(Arrays.deepToString(matrix));
50+
int[][] matrix2 = {
51+
{1, 2, 3}, {4, 0, 6}, {7, 8, 9}
52+
};
53+
setZeros(matrix1);
54+
setZeros(matrix2);
55+
System.out.println(Arrays.deepToString(matrix1));
56+
System.out.println(Arrays.deepToString(matrix2));
5257
}
5358
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
**Problem statement:**
2+
Given an `m x n` matrix of integers `matrix`, if an element is `0`, set its entire row and column to `0`'s.
3+
4+
**Note:** You must update the matrix in-place using constant space solution(`O(1)`).
5+
6+
## Examples:
7+
Example1:
8+
9+
Input: matrix = [
10+
[1, 0, 1], [1, 0, 1], [0, 1, 1]
11+
]
12+
13+
Output: [
14+
[0,0,0],
15+
[0,0,0],
16+
[0,0,0]
17+
]
18+
19+
![Screenshot](../../../../images/set-matrix-zeros1.png)
20+
21+
Example2:
22+
23+
Input: matrix = [
24+
[1, 2, 3], [4, 0, 6], [7, 8, 9]
25+
]
26+
27+
Output: [
28+
[1, 0, 3], [0, 0, 0], [7, 0, 9]
29+
]
30+
31+
![Screenshot](../../../../images/set-matrix-zeros2.png)
32+
33+
34+
**Algorithmic Steps**
35+
This problem is solved by in-place alogorithm in which first row and first column of given matrix acts as markers for setting zeroes in cells. Since the first cell is used to track the first column zeros, we need to take an extra boolean marker for first row zeroes. The algorithmic approach can be summarized as follows:
36+
37+
1. Create a function(`setZeroes`) by accepting the `m*n` matrix as input parameter.
38+
39+
2. Store the number of rows(`rows`) and columns(`cols`) of a matrix for iteration purpose. The first row and first column acts as markers to indicate which rows and columns should set to zero. The boolean marker `rowZero` is used as a zero marker for first row because the first cell is used as marker for first column cells.
40+
41+
3. Iterate over each cell of a matrix to mark which columns and rows to be set to zero,
42+
1. If the cell value is zero, set the respective column's first row value to zero.
43+
2. If the cell's row is greater than zero, set the respective row's first column value to zero.
44+
3. Otherwise, set `rowZero` to `true` indicating that first row marked for zeros.
45+
46+
4. Iterate each cell again except first row and first column, set the cell value to zero based on first row and first column values.
47+
48+
5. Set zeros to first column if first cell's value is zero.
49+
6. Set zeros to first row if the boolean marker `rowZero` is `true`.
50+
7. At this stage, given matrix is updated with zeros for respective rows and columns without using additional space.
51+
52+
**Time and Space complexity:**
53+
This algorithm has a time complexity of `O(m*n))`, where `m` is the number of rows and `n` is the number of columns in the given matrix. This is because each cell visited twice, once to mark the rows and columns that should be set to zero and once to actually set the zeroes in cells.
54+
55+
It requires `O(1)` constant space complexity irrespective of the matrix size. This is becuase it uses only one variable(`rowZero`),which is used to mark the first row cells to be zero or not.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package java1.algorithms.matrix.spiralMatrix;
2+
3+
import java.util.*;
4+
5+
public class SpiralMatrix {
6+
// TC: O(m*n) SC: O(1)
7+
private static List<Integer> spiralOrder(int[][] matrix) {
8+
List<Integer> traversal = new ArrayList<>();
9+
int left =0, right = matrix[0].length-1;
10+
int top =0, bottom= matrix.length-1;
11+
12+
while(left <= right && top <= bottom) {
13+
// Top row elements
14+
for(int i=left; i<=right; i++) {
15+
traversal.add(matrix[top][i]);
16+
}
17+
18+
top++;
19+
20+
// Last column elements
21+
for(int i=top; i<=bottom; i++) {
22+
traversal.add(matrix[i][right]);
23+
}
24+
25+
right--;
26+
27+
if(left<=right && top<=bottom) {
28+
// Last row elements
29+
for(int i= right; i>=left; i--) {
30+
traversal.add(matrix[bottom][i]);
31+
}
32+
33+
bottom--;
34+
35+
// First column elements
36+
for(int i= bottom; i>=top; i--) {
37+
traversal.add(matrix[i][left]);
38+
}
39+
40+
left++;
41+
}
42+
43+
}
44+
return traversal;
45+
}
46+
47+
public static void main(String[] args) {
48+
int[][] matrix1 = {
49+
{1, 2}, {3, 4}
50+
};
51+
int[][] matrix2 = {
52+
{1, 2, 3}, {4, 5, 6}, {7, 8, 9}
53+
};
54+
int[][] matrix3 = {
55+
{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}
56+
};
57+
58+
System.out.println(spiralOrder(matrix1));
59+
System.out.println(spiralOrder(matrix2));
60+
System.out.println(spiralOrder(matrix3));
61+
}
62+
}

0 commit comments

Comments
 (0)