<offer4> 04_FindInPartiallySortedMatrix

清風oo發表於2018-11-02
 1 #include<cstdio>
 2 
 3 bool Find(int* matrix, int rows, int columns, int number)
 4 {
 5     bool result = false;
 6     if(matrix != nullptr && rows > 0 && columns > 0)
 7     {
 8         int row_begin = 0;
 9         int col_begin = columns - 1; //3  [0, 3]
10 
11         while (columns >= 0 && row_begin < rows)
12         {
13             if (matrix[row_begin*columns + col_begin] == number)
14             {
15                 result = true;
16                 return result;
17             }
18             else if (matrix[row_begin*columns + col_begin] > number)
19                 col_begin--; //  2 1
20             else
21                 row_begin++;
22         }
23     }
24     return result;
25 }
26 
27 void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected)
28 {
29     if (testName != nullptr)
30         printf("%s begins: ", testName);
31     bool result = Find(matrix, rows, columns, number);
32     if (result == expected)
33     {
34         printf("passed.\n");
35     }
36     else
37         printf("failed.\n");
38 }
39 
40 void Test1()
41 {
42     int matrix[][4] = { {1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15} };
43     Test("Test1", (int*)matrix, 4, 4, 7, true);
44 }
45 void Test2()
46 {
47     int matrix[][4] = { { 1,2,8,9 },{ 2,4,9,12 },{ 4,7,10,13 },{ 6,8,11,15 } };
48     Test("Test1", (int*)matrix, 4, 4, 5, false);
49 }
50 void Test3()
51 {
52     int matrix[][4] = { { 1,2,8,9 },{ 2,4,9,12 },{ 4,7,10,13 },{ 6,8,11,15 } };
53     Test("Test1", (int*)matrix, 4, 4, 1, true);
54 }
55 void Test4()
56 {
57     int matrix[][4] = { { 1,2,8,9 },{ 2,4,9,12 },{ 4,7,10,13 },{ 6,8,11,15 } };
58     Test("Test1", (int*)matrix, 4, 4, 15, true);
59 }
60 void Test5()
61 {
62     int matrix[][4] = { { 1,2,8,9 },{ 2,4,9,12 },{ 4,7,10,13 },{ 6,8,11,15 } };
63     Test("Test1", (int*)matrix, 4, 4, 0, false);
64 }
65 void Test6()
66 {
67     int matrix[][4] = { { 1,2,8,9 },{ 2,4,9,12 },{ 4,7,10,13 },{ 6,8,11,15 } };
68     Test("Test1", (int*)matrix, 4, 4, 16, false);
69 }
70 void Test7()
71 {
72     Test("Test1", nullptr, 0, 0, 16, false);
73 }
74 int main(int argc, char* argv[])
75 {
76     Test1();
77     Test2();
78     Test3();
79     Test4();
80 
81     Test5();
82     Test6();
83     Test7();
84     return 0;
85 }