东方博宜OJ 1360:卒的遍历 ← DFS

【题目来源】
https://oj.czos.cn/p/1360

【题目描述】
在一张 n×m 的棋盘上(如 6 行 7 列)的最左上角(1, 1) 的位置有一个卒。

boyi1360

该卒只能向下或者向右走,且卒采取的策略是先向下,下边走到头就向右,请问从(1, 1) 点走到(n, m)点可以怎样走,输出这些走法。

【输入格式】
两个整数 n,m 代表棋盘大小(3≤n≤8,3≤m≤8)

【输出格式】
卒的行走路线。

【输入样例】
3 3

【输出样例】
1:1,1->2,1->3,1->3,2->3,3
2:1,1->2,1->2,2->3,2->3,3
3:1,1->2,1->2,2->2,3->3,3
4:1,1->1,2->2,2->3,2->3,3
5:1,1->1,2->2,2->2,3->3,3
6:1,1->1,2->1,3->2,3->3,3

【数据范围】
3≤n≤8,3≤m≤8

【算法分析】
● dfs 算法通常表现为复杂的递归函数形式,因此掌握“递归”是理解 dfs 算法的基础。

● dfs 算法的常用模板,如下所示。

void dfs(int step) {
    判断边界 {
        输出解
    }

    尝试每一种可能 {
        满足check条件{
            标记
            继续下一步:dfs(step+1)
            恢复初始状态(回溯的时候要用到)
        }
    }
}


【算法代码】

#include<bits/stdc++.h>
using namespace std;

int dx[]= {1,0},dy[]= {0,1};
int p[20][2]; //p[i][.] is i-th point's coord
int step;
int n,m;

void print(int cnt) { //info of cnt points
    step++;
    cout<<step<<":";
    for(int i=1; i<cnt; i++) {
        cout<<p[i][0]<<","<<p[i][1]<<"->";
    }
    cout<<n<<","<<m<<endl; //the cnt-th point's coord
}

void dfs(int x,int y,int cnt) {
    p[cnt][0]=x;
    p[cnt][1]=y;
    if(x==n && y==m) {
        print(cnt);
        return;
    }

    int tx,ty;
    for(int i=0; i<2; i++) {
        tx=x+dx[i];
        ty=y+dy[i];
        if(tx>=1 && tx<=n && ty>=1 && ty<=m) {
            dfs(tx,ty,cnt+1);
        }
    }
}

int main() {
    cin>>n>>m;
    dfs(1,1,1);
    return 0;
}

/*
in:
3 3

out:
1:1,1->2,1->3,1->3,2->3,3
2:1,1->2,1->2,2->3,2->3,3
3:1,1->2,1->2,2->2,3->3,3
4:1,1->1,2->2,2->3,2->3,3
5:1,1->1,2->2,2->2,3->3,3
6:1,1->1,2->1,3->2,3->3,3
*/





【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/118736059
https://www.bilibili.com/video/av396891158
https://blog.csdn.net/lailaike08/article/details/135714297




 

posted @ 2025-12-27 20:51  Triwa  阅读(55)  评论(0)    收藏  举报