Consider a \(6 \times 6\) checkerboard with six pieces placed such that each row, each column, and each diagonal (including both main diagonals and all other diagonals) contains at most one piece.
The above layout can be described by the sequence \(\{2,4,6,1,3,5\}\), where the \(i\)-th number indicates that there is a piece in column \(a_i\) of row \(i\), as shown below:
Row index \(i\): \(\{1,2,3,4,5,6\}\)
Column index \(a_i\): \(\{2,4,6,1,3,5\}\)
This is just one possible arrangement. Write a program to find all such arrangements and output them using the above serialization method, sorted in lexicographical order. You only need to output the first \(3\) solutions and print the total number of solutions on the last line. Special attention: you need to optimize your program to ensure efficiency for larger board sizes.
// This code is a DFS implementation of the backtracking method#include<iostream>usingnamespacestd;intans[14],check[3][28]={0},sum=0,n;voideq(intline){if(line>n){// If n rows have been searchedsum++;if(sum>3)return;else{for(inti=1;i<=n;i++)cout<<ans[i]<<' ';cout<<'\n';return;}}for(inti=1;i<=n;i++){if((!check[0][i])&&(!check[1][line+i])&&(!check[2][line-i+n])){// Determine if placing at a certain position is legalans[line]=i;check[0][i]=1;check[1][line+i]=1;check[2][line-i+n]=1;eq(line+1);// Backtrack after recursion to facilitate the next round of recursioncheck[0][i]=0;check[1][line+i]=0;check[2][line-i+n]=0;}}}intmain(){cin.tie(nullptr)->sync_with_stdio(false);cin>>n;eq(1);cout<<sum;return0;}
Given a maze of size \(N \times M\) with \(T\) obstacles (which cannot be passed through), start coordinates and end coordinates, and the condition that each cell can be visited at most once, find the number of distinct paths from the start to the end. Movement in the maze is allowed in four directions: up, down, left, and right, one cell at a time. It is guaranteed that the starting cell has no obstacle.
// This code is a BFS implementation using backtracking#include<cstring>#include<iostream>#include<queue>usingnamespacestd;intn,m,k,x,y,a,b,ans;intdx[4]={0,0,1,-1},dy[4]={1,-1,0,0};// Four directionsboolvis[6][6];structoo{intx,y,used[6][6];};oosa;voidbfs(){queue<oo>q;sa.x=x;sa.y=y;sa.used[x][y]=1;q.push(sa);while(!q.empty()){// BFS queueoonow=q.front();q.pop();for(inti=0;i<4;i++){// Enumerate moving in four directionsintsx=now.x+dx[i];intsy=now.y+dy[i];if(now.used[sx][sy]||vis[sx][sy]||sx==0||sy==0||sx>n||sy>m)continue;if(sx==a&&sy==b){ans++;continue;}sa.x=sx;sa.y=sy;memcpy(sa.used,now.used,sizeof(now.used));sa.used[sx][sy]=1;q.push(sa);// Assume moving in this direction, push into BFS queue}}}intmain(){cin.tie(nullptr)->sync_with_stdio(false);cin>>n>>m>>k;cin>>x>>y>>a>>b;for(inti=1,aa,bb;i<=k;i++){cin>>aa>>bb;vis[aa][bb]=true;// Obstacle positions are impassable}bfs();cout<<ans;return0;}