#include<bits/stdc++.h>usingnamespace std;int n, a[55];voiddfs(int step,int x,int last){if(x ==0){printf("%d=%d", n, a[1]);for(int i =2; i <= step-1; i++){printf("+%d", a[i]);}printf("\n");return;}for(int i =min(last, x); i >=1; i--){a[step]= i;dfs(step+1, x-i, i);}}intmain(){cin >> n;dfs(1, n,1e8);return0;}
#include<iostream>#include<queue>usingnamespace std;structNode{int x, y, step;};int n;int a[110][110];int vis[110][110];int x1, y1, x2, y2;int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};queue <Node> q;voidbfs(){q.push({x1, y1,0});vis[x1][y1]=1;while(!q.empty()){auto[fx, fy, fstep]= q.front();q.pop();if(fx == x2 && fy == y2){cout << fstep;return;}for(int i =0; i <4; i++){int tx = fx + dx[i];int ty = fy + dy[i];if(tx >=1&& tx <= n && ty >=1&& ty <= n &&!vis[tx][ty]&&!a[tx][ty]){vis[tx][ty]=1;q.push({tx, ty, fstep+1});}}}}intmain(){cin >> n;for(int i =1; i <= n; i++)for(int j =1; j <= n; j++)cin >> a[i][j];cin >> x1 >> y1 >> x2 >> y2;bfs();return0;}
三、例题
1. [蓝桥杯 2016 国 AC] 路径之谜
#include<iostream>#include<vector>usingnamespace std;int n, len;int vis[40][40];int rs[40], cs[40];int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};
vector <int> path;voiddfs(int x,int y){if(x == n && y == n && len ==0){for(auto v : path){cout << v <<" ";}return;}for(int i =0; i <4; i++){int tx = x + dx[i];int ty = y + dy[i];if(vis[tx][ty]|| rs[tx]==0|| cs[ty]==0)continue;path.push_back((tx-1)*n+ty-1);vis[tx][ty]=1, rs[tx]--, cs[ty]--, len--;dfs(tx, ty);vis[tx][ty]=0, rs[tx]++, cs[ty]++, len++;path.pop_back();}}intmain(){cin >> n;for(int i =1; i <= n; i++){cin >> cs[i];len += cs[i];vis[0][i]= vis[n+1][i]=1;}for(int i =1; i <= n; i++){cin >> rs[i];vis[i][0]= vis[i][n+1]=1;}path.push_back(0);vis[1][1]=1, rs[1]--, cs[1]--, len--;dfs(1,1);return0;}