一些经典搜索题目集

本文介绍了多个基于搜索的经典算法题目,包括POJ1979 Red and Black的连通块问题,P1443马的遍历,P1135奇怪的电梯等,涉及深搜、广搜等解题方法,并提供了相应的C++代码实现。
摘要由CSDN通过智能技术生成

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}, {
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值