<offer4> 04_FindInPartiallySortedMatrix
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 }
标签:
OFFER
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix