-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindInMatrix.cs
More file actions
70 lines (64 loc) · 2.02 KB
/
FindInMatrix.cs
File metadata and controls
70 lines (64 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Problem.Arrays
{
[TestClass]
public class FindInSortedMatrix
{
/// <summary>
/// The given matrix is sorted column from right
/// </summary>
/// <param name="matrix"></param>
/// <param name="target"></param>
public bool FindValueInSortedMatrix(int[,] matrix, int target)
{
/// [
/// [1, 4, 7, 11, 15],
/// [2, 5, 8, 12, 19],
/// [3, 6, 9, 16, 22],
/// [10, 13, 14, 17, 24],
/// [18, 21, 23, 26, 30]
/// ]
bool isTargetFound = false;
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(1);
// start from left bottom.
int row = rowLength - 1;
int col = 0;
while(row > 0 && col < colLength)
{
if( matrix[row, col] > target)
{
row--;
}
else if(matrix[row, col] < target)
{
col++;
}
else
{
isTargetFound = true;
break;
}
}
return isTargetFound;
}
[TestMethod]
public void TestFindValueInSortedMatrix()
{
int[,] matrix = {
{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},
{10, 13, 14, 17, 24},
{18, 21, 23, 26, 30}
};
Assert.IsTrue(this.FindValueInSortedMatrix(matrix, 5));
Assert.IsFalse(this.FindValueInSortedMatrix(matrix, 50));
}
}
}