Solution of ZOJ 2850 Beautiful Meadow

Solution of ZOJ 2850 Beautiful Meadow_第1张图片
Tom's Meadow

Tom has a meadow in his garden. He divides it into N * M squares. Initially all the squares were covered with grass. He mowed down the grass on some of the squares and thinks the meadow is beautiful if and only if

  1. Not all squares are covered with grass.
  2. No two mowed squares are adjacent.

Two squares are adjacent if they share an edge. Here comes the problem: Is Tom's meadow beautiful now?

Input

The input contains multiple test cases!

Each test case starts with a line containing two integers N, M (1 <= N, M <= 10) separated by a space. There follows the description of Tom's Meadow. There're N lines each consisting of M integers separated by a space. 0(zero) means the corresponding position of the meadow is mowed and 1(one) means the square is covered by grass.

A line with N = 0 and M = 0 signals the end of the input, which should not be processed

Output

One line for each test case.

Output "Yes" (without quotations) if the meadow is beautiful, otherwise "No"(without quotations).

Sample Input

2 2
1 0
0 1
2 2
1 1
0 0
2 3
1 1 1
1 1 1
0 0

Sample Output

Yes
No
No

Source: Zhejiang Provincial Programming Contest 2007

 

 

 

分析:本题关键点在于统计0的个数以及搜索是否存在纵向和横向两个方向之一存在连续0的情况。

下面给出我的实现代码:

 

#include <iostream> #include <cstdio> using namespace std; bool has_conn_edge( int *** meadow, int rows, int cols ) { bool res = false; for( int i = 0; i < rows - 1 && ! res; ++i ) { for( int j = 0; j < cols - 1; ++j ) { if( (* meadow)[i][j] == 0 && ( (* meadow)[i][j+1] == 0 || (* meadow)[i+1][j] == 0 ) ) { res = true; break; } } } // scan the last column for( int i = 0; i < rows - 1 && ! res; ++i ) { if( (* meadow)[i][cols-1] == 0 && (* meadow)[i+1][cols-1] == 0 ) { res = true; break; } } // scan the last row for( int j = 0; j < cols - 1 && ! res; ++j ) { if( (* meadow)[rows-1][j] == 0 && (* meadow)[rows-1][j+1] == 0 ) { res = true; break; } } return res; } int main() { int rows, cols; int ** meadow = NULL; bool is_beautiful = true; while( cin >> rows >> cols ) { if( rows == 0 || cols == 0 ) break; meadow = new int*[rows]; for( int i = 0; i < rows; ++i ) meadow[i] = new int[cols]; int num_zeros = 0; for( int i = 0; i < rows; ++i ) { for( int j = 0; j < cols; ++j ) { cin >> meadow[i][j]; if( meadow[i][j] == 0 ) ++num_zeros; } } is_beautiful = ( num_zeros > 0 ) && ! has_conn_edge( &meadow, rows, cols ); if( is_beautiful ) printf("Yes/n"); else printf("No/n"); for( int i = 0; i < rows; ++i ) delete[] meadow[i]; delete [] meadow; meadow = NULL; } return 0; }

你可能感兴趣的:(Solution of ZOJ 2850 Beautiful Meadow)