title recall: Aerial photograph of a rectangular open-air view, with the number 0 or 1 to see the space or the roof, the adjacent roof belongs to the same house, on the diagonal roof does not belong to the same house (which is also in line with the actual), now enter the size of the open space, And then enter the layout of the top view of the rectangle and ask us to output how many houses there are in this rectangular space.
Test Case:
TestCase 1:
Input:
5 5
0 1 0) 0 0
0 0 1) 1 0
0 0 0) 1 0
0 0 0) 0 0
0 0 0) 0 0
Expected Return Value:
2
TestCase 2:
Input:
5 6
0 1 0 0 1 0
0 1 1 1 0 0
0 0 0 1 0 0
0 0 0 0 1 1
0 0 0 0 1 1
Expected Return Value:
3
is not a problem, online someone to do with recursion, too troublesome, not high efficiency, here I use space for time, with two flags array to flag the current position to the left and top whether there is a roof, start from the top left to scan, dynamically update the flag array, only when the left and top of a position does not have a roof to count, The number of houses is drawn at the end of the scan. My program successfully passed the official two test cases, but later I found that my two flags array in some input situations will overflow, are tears, corrected Java source code as follows:
ImportJava.util.Scanner; Public classMain { Public Static voidMain (string[] args) {//TODO auto-generated Method StubScanner Scan=NewScanner (system.in); while(Scan.hasnext ()) {introw =Scan.nextint (); intCol =Scan.nextint (); int[] Matrix =New int[Row][col]; for(inti = 0; i < row; i++) { for(intj = 0; J < Col; J + +) {Matrix[i][j]=Scan.nextint (); }} System.out.println (Counthourse.docounthourse (row, col, Matrix)); } scan.close (); }}classCounthourse { Public Static intDocounthourse (intRowintColint[] matrix) { //Note: Add 1 to prevent cross-border Boolean[] Leftroof =New Boolean[Row + 1] [col + 1];//flag Whether there is a roof on the left side of the position Boolean[] Toproof =New Boolean[Row + 1] [col + 1];//flag If there is a roof above the position intCount = 0; for(inti = 0; i < row; i++) { for(intj = 0; J < Col; J + +) { if(Matrix[i][j] = = 1) {leftroof[i][j+ 1] =true; Leftroof[i+ 1][j] =true; if((!leftroof[i][j]) && (!Toproof[i][j])) Count++; } } } returncount; }}
ZTE holds the Blue Sword Road in the preliminary question--several houses