prakash.4's blog

By prakash.4, history, 5 years ago, In English

I don't know why i am getting wrong answer. Could anyone help me in finding out what's wrong in this code.

This is the link to the question. https://www.hackerearth.com/problem/algorithm/move-the-knight/

Below is my code.

include <bits/stdc++.h>

define mod 1000000007

using namespace std;

void f(int r,int c,vector<vector> &visited,int &cnt) { if(r >= 1 && r <= 8 && c >= 1 && c <= 8 && visited[r][c] == false) { visited[r][c] = true; cnt++; f(r+1,c+2,visited,cnt); f(r+1,c-2,visited,cnt); f(r-1,c+2,visited,cnt); f(r-1,c-2,visited,cnt); f(r+2,c+1,visited,cnt); f(r-2,c+1,visited,cnt); f(r+2,c-1,visited,cnt); f(r-2,c-1,visited,cnt); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--) { int r,c,cnt = -1; cin>>r>>c; vector< vector > visited(9); for(int i = 1; i <= 8; ++i) { vector temp(9); visited[i] = temp; } f(r,c,visited,cnt); cout<<cnt<<"\n"; for(int i = 1; i <= 8; ++i) for(int j = 1; j <= 8; ++j) if(visited[i][j] == true) cout<<i<<" "<<j<<" "; cout<<"\n"; } return 0; }

Thanks.

  • Vote: I like it
  • -31
  • Vote: I do not like it

»
5 years ago, # |
  Vote: I like it +19 Vote: I do not like it

Please make your code clear, or no one would like to read it.

You can use the "block" function.It will work as below:

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

void f(int r,int c,vector<vector> &visited,int &cnt) { 
    if(r >= 1 && r <= 8 && c >= 1 && c <= 8 && visited[r][c] == false) { 
        visited[r][c] = true; 
        cnt++; 
        f(r+1,c+2,visited,cnt); 
        f(r+1,c-2,visited,cnt); 
        f(r-1,c+2,visited,cnt); 
        f(r-1,c-2,visited,cnt); 
        f(r+2,c+1,visited,cnt); 
        f(r-2,c+1,visited,cnt); 
        f(r+2,c-1,visited,cnt); 
        f(r-2,c-1,visited,cnt); 
    } 
} 
int main() { 
    ios_base::sync_with_stdio(false); 
    cin.tie(NULL); cout.tie(NULL); 
    int t; cin>>t; 
    while(t--) { 
        int r,c,cnt = -1; 
        cin>>r>>c; 
        vector< vector > visited(9); 
        for(int i = 1; i <= 8; ++i) { 
            vector temp(9); 
            visited[i] = temp; 
        } 
        f(r,c,visited,cnt); 
        cout<<cnt<<"\n"; 
        for(int i = 1; i <= 8; ++i) 
            for(int j = 1; j <= 8; ++j) 
                if(visited[i][j] == true) cout<<i<<" "<<j<<" "; 
        cout<<"\n"; 
    } 
    return 0; 
}

And if you like, you can make a spoiler:

Spoiler

That will be better and you will (probably) not keep getting downvotes.

Always preview your comment/blog before posting.