{ "title": "C++代码实现判断10x10矩阵中被1包围的0的数量", "description": "本文提供C++代码,用于计算一个10x10的矩阵中,被1包围的0的数量,包括被最外圈的1包围的0。代码简洁易懂,并附带详细的代码注释。", "keywords": "C++, 矩阵, 10x10, 0, 1, 统计, 包围, 代码, 算法", "content": "下面是一个用C++编写的解决方案:\n\ncpp\n#include <iostream>\nusing namespace std;\n\nint countSurroundedZeros(int matrix[10][10]) {\n int count = 0;\n \n // 遍历矩阵中的每个元素\n for(int i=0; i<10; i++) {\n for(int j=0; j<10; j++) {\n if(matrix[i][j] == 0) {\n // 判断当前元素是否被1围住\n bool surrounded = true;\n \n // 判断上下左右四个位置是否为1\n if(i > 0 && matrix[i-1][j] != 1) {\n surrounded = false;\n }\n if(i < 9 && matrix[i+1][j] != 1) {\n surrounded = false;\n }\n if(j > 0 && matrix[i][j-1] != 1) {\n surrounded = false;\n }\n if(j < 9 && matrix[i][j+1] != 1) {\n surrounded = false;\n }\n \n // 如果当前元素被1围住,则计数加一\n if(surrounded) {\n count++;\n }\n }\n }\n }\n \n return count;\n}\n\nint main() {\n int matrix[10][10];\n \n // 输入矩阵元素\n for(int i=0; i<10; i++) {\n for(int j=0; j<10; j++) {\n cin >> matrix[i][j];\n }\n }\n \n int surroundedZerosCount = countSurroundedZeros(matrix);\n cout << "被1围住的0的数量为:" << surroundedZerosCount << endl;\n \n return 0;\n}\n\n\n这个程序首先通过cin从标准输入中读取一个10x10的矩阵,然后调用countSurroundedZeros函数来计算被1围住的0的数量,最后将结果输出到标准输出中。"}


原文地址: https://www.cveoy.top/t/topic/pNm6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录