| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.SetMatrixZeroes; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SetMatrixZeroesInPlace : ISetMatrixZeroes |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m * n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="matrix"></param> |
| | 22 | | public void SetZeroes(int[][] matrix) |
| 2 | 23 | | { |
| 2 | 24 | | var firstRowZero = false; |
| 2 | 25 | | var firstColZero = false; |
| | 26 | |
|
| 16 | 27 | | for (var i = 0; i < matrix.Length; i++) |
| 6 | 28 | | { |
| 54 | 29 | | for (var j = 0; j < matrix[i].Length; j++) |
| 21 | 30 | | { |
| 21 | 31 | | if (matrix[i][j] != 0) |
| 18 | 32 | | { |
| 18 | 33 | | continue; |
| | 34 | | } |
| | 35 | |
|
| 3 | 36 | | if (i == 0) |
| 2 | 37 | | { |
| 2 | 38 | | firstRowZero = true; |
| 2 | 39 | | } |
| | 40 | |
|
| 3 | 41 | | if (j == 0) |
| 1 | 42 | | { |
| 1 | 43 | | firstColZero = true; |
| 1 | 44 | | } |
| | 45 | |
|
| 3 | 46 | | matrix[i][0] = 0; |
| 3 | 47 | | matrix[0][j] = 0; |
| 3 | 48 | | } |
| 6 | 49 | | } |
| | 50 | |
|
| 12 | 51 | | for (var i = 1; i < matrix.Length; i++) |
| 4 | 52 | | { |
| 28 | 53 | | for (var j = 1; j < matrix[i].Length; j++) |
| 10 | 54 | | { |
| 10 | 55 | | if (matrix[i][0] == 0 || matrix[0][j] == 0) |
| 5 | 56 | | { |
| 5 | 57 | | matrix[i][j] = 0; |
| 5 | 58 | | } |
| 10 | 59 | | } |
| 4 | 60 | | } |
| | 61 | |
|
| 2 | 62 | | if (firstColZero) |
| 1 | 63 | | { |
| 9 | 64 | | foreach (var row in matrix) |
| 3 | 65 | | { |
| 3 | 66 | | row[0] = 0; |
| 3 | 67 | | } |
| 1 | 68 | | } |
| | 69 | |
|
| 2 | 70 | | if (firstRowZero) |
| 1 | 71 | | { |
| 10 | 72 | | for (var j = 0; j < matrix[0].Length; j++) |
| 4 | 73 | | { |
| 4 | 74 | | matrix[0][j] = 0; |
| 4 | 75 | | } |
| 1 | 76 | | } |
| 2 | 77 | | } |
| | 78 | | } |