POJ1979 Red and Black
题意:简单的搜索,经典连通块问题。
做法:深搜广搜都可,下面是简短的深搜代码,POJ交题不能用万能头文件呀呀呀。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
using namespace std;
typedef long long ll;
typedef pair<ll, int> pli;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
template<class T>
void read(T &res) {
int f = 1; res = 0;
char c = getchar();
while(c < '0' || c > '9') {
if(c == '-') f = -1; c = getchar(); }
while(c >= '0' && c <= '9') {
res = res * 10 + c - '0'; c = getchar(); }
res *= f;
}
const int N = 24;
int ne[4][2] = {
1, 0, -1, 0, 0, -1, 0, 1};
int n, m, res;
int vis[N][N];
char mp[N][N];
void dfs(int x, int y) {
res++;
for(int i = 0; i < 4; ++i) {
int tx = x + ne[i][0];
int ty = y + ne[i][1];
if(tx < 1 || ty < 1 || tx > m || ty > n || mp[tx][ty] != '.' || vis[tx][ty])
continue;
vis[tx][ty] = 1;
dfs(tx, ty);
}
}
int main() {
while(scanf("%d%d", &n, &m), n && m) {
res = 0;
memset(vis, 0, sizeof vis);
for(int i = 1; i <= m; ++i) {
scanf("%s", mp[i] + 1);
}
for(int i = 1; i <= m; ++i) {
for(int j = 1; j <= n; ++j) {
if(mp[i][j] == '@') {
dfs(i, j); break; }
}
}
printf("%d\n", res);
}
return 0;
}
P1443 马的遍历
题意:有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
做法:敲简单,8个方向上广搜,手痒写了一发Java,有一个点T了…洛谷还是对Java不太友好啊,下面C++代码。
代码:
#include<bits/stdc++.h>
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
using namespace std;
typedef long long ll;
typedef pair<ll, int> pli;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
template<class T>
void read(T &res) {
int f = 1; res = 0;
char c = getchar();
while(c < '0' || c > '9') {
if(c == '-') f = -1; c = getchar(); }
while(c >= '0' && c <= '9') {
res = res * 10 + c - '0'; c = getchar(); }
res *= f;
}
const int N = 405;
int ne[8][2] = {
{
1, 2}, {
1, -2}, {
-1, 2}, {
-1, -2}, {