写在前面:本文记录一些贪心算法的练习题,欢迎讨论!本系列系本人原创,如需转载或引用,请注明原作者及文章出处。本文持续更新。
一、Red and Black (POJ1979)
描述Write a program to count the number of black tiles which he can reach by repeating the moves described above.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
45
59
6
13
#include<iostream>
#include<algorithm>
using namespace std;
int w, h, beginx, beginy, arr[25][25], num;
char a[25][25];
void dfs(int x, int y)
{
if (x > 0 && arr[x - 1][y] == 1)
{
num++;
arr[x - 1][y] = 0;
dfs(x - 1, y);
}
if (x < h - 1 && arr[x + 1][y] == 1)
{
num++;
arr[x + 1][y] = 0;
dfs(x + 1, y);
}
if (y > 0 && arr[x][y - 1] == 1)
{
num++;
arr[x][y - 1] = 0;
dfs(x, y - 1);
}
if (y < w - 1 && arr[x][y + 1] == 1)
{
num++;
arr[x][y + 1] = 0;
dfs(x, y + 1);
}
}
int main()
{
while (1)
{
cin >> w >> h;
if (w == 0 && h == 0)
break;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
{
cin >> a[i][j];
if (a[i][j] == '@')
{
beginx = i;
beginy = j;
}
if (a[i][j] == '#' || a[i][j] == '@')
arr[i][j] = 0;
else
arr[i][j] = 1;
}
num = 1;
dfs(beginx, beginy);
cout << num << endl;
}
return 0;
}
二、棋盘问题 (POJ1321)
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。
2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1
2
1
#include<iostream>
#include<algorithm>
using namespace std;
int n, k, chess[10], num;
char a[10][10];
void dfs(int row, int k)
{
if (k == 0)
{
num++;
return;
}
for (int i = row; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j] == '#' && chess[j] == 1)
{
chess[j] = 0;
dfs(i + 1, k - 1);
chess[j] = 1;
}
}
}
}
int main()
{
while (1)
{
cin >> n >> k;
if (n == -1 && k == -1)
break;
for (int i = 0; i < n; i++)
chess[i] = 0;
num = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
if (a[i][j] == '#')
chess[j] = 1;
}
dfs(0, k);
cout << num << endl;
}
return 0;
}