Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Conversation opened. 1 read message.
- Skip to content
- Using Daffodil International University Mail with screen readers
- 9 of 1,417
- Fwd: Backtracking Codes
- Inbox
- x
- Md. Erfanul Islam Bhuiyan 181-15-10777 <erfanul15-10777@diu.edu.bd>
- AttachmentsDec 5, 2018, 6:17 PM (1 day ago)
- to me
- ---------- Forwarded message ---------
- From: Nazmus Sakib 181-15-10817 <nazmus15-10817@diu.edu.bd>
- Date: Tue, Dec 4, 2018 at 5:22 PM
- Subject: Backtracking Codes
- To: <alif15-10730@diu.edu.bd>
- Cc: <erfanul15-10777@diu.edu.bd>, <imran15-10627@diu.edu.bd>, <tanima15-10733@diu.edu.bd>, <aziz15-8396@diu.edu.bd>
- 6 Attachments
- #include <bits/stdc++.h>
- using namespace std;
- int x[] = {-2,-2,1,-1,-1,1,2,2};
- int y[] = {1,-1,-2,-2,2,2,-1,1};
- int A[12][12] = {
- {0,1,0,1,1},
- {1,1,0,-1,1},
- {0,1,1,1,0},
- {0,1,0,1,0},
- {0,0,1,0,0},
- };
- bool isValid(int row,int col){
- if(row < 0 or row > 4 or col < 0 or col > 4) return false;
- return true;
- }
- bool solution(){
- if(A[0][0] == 1 and
- A[0][1] == 1 and
- A[0][2] == 1 and
- A[0][3] == 1 and
- A[0][4] == 1 and
- A[1][1] == 1 and
- A[1][2] == 1 and
- A[1][3] == 1 and
- A[1][4] == 1 and
- A[2][3] == 1 and
- A[2][4] == 1 and
- A[3][4] == 1 and
- A[2][2] == -1
- ) return true;
- return false;
- }
- bool Solve(int totalMoves,int movesSoFar,int row,int col,int lastRow, int lastCol){
- if(movesSoFar > totalMoves)
- return false;
- if(solution()){
- return true;
- }
- // cout << totalMoves << endl;
- for(int i = 0; i < 8; i++){
- int dx = row + x[i];
- int dy = col + y[i];
- if(dx != lastRow and dy != lastCol and isValid(dx,dy)){
- swap(A[dx][dy],A[row][col]);
- if(Solve(totalMoves,movesSoFar+1,dx,dy,row,col)) return true;
- swap(A[dx][dy],A[row][col]);
- }
- }
- return false;
- }
- int main()
- {
- int ans = -1;
- for(int totalMoves = 0; totalMoves < 12; totalMoves++){
- if(Solve(totalMoves,0,1,3,1,3)){
- ans = totalMoves;
- break;
- }
- }
- cout << ans << endl;
- }
- KnightMove.cpp
- Displaying KnightMove.cpp.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement