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

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef pair<int, int> P;

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()

ll mod = 1000000007;
int main(){
  int n; cin >> n;
  vector <ll> a(n);
  rep(i, n){
    cin >> a[i];
    a[i]++;
  }
  vector <ll> num(n+1);
  num[0] = 3;
  ll ans = 1;
  rep(i, n){
    if (num[a[i]-1] < 0){
      cout << 0 << endl;
      return 0;
    }
    ans *= num[a[i]-1];
    ans %= mod;
    num[a[i]-1]--;
    num[a[i]]++;
  }
  cout << ans <<endl;
}
/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author rahdirigs
 */

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

template <typename T> void s_max(T& a, T b) {
	if (a < b) {
		a = b;
	}
}

class TaskU {
public:
	int N;
	vector<vector<int>> a;
	vector<ll> dp, scores;
	vector<int> rem;

	void solve(std::istream& in, std::ostream& out) {
		in >> N;
		a.resize(N, vector<int> (N));
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				in >> a[i][j];
			}
		}
		scores.resize(1 << N, 0);
		dp.resize(1 << N, 0);
		pre_calc();
		for (int mask = 0; mask < (1 << N); mask++) {
			rem.clear();
			for (int i = 0; i < N; i++) {
				if (!(mask & (1 << i))) rem.push_back(i);
			}
			rec(0, dp[mask], mask, 0);
		}
		out << dp[(1 << N) - 1];
	}

	void pre_calc() {
		for (int mask = 0; mask < (1 << N); mask++) {
			for (int i = 0; i < N; i++) {
				for (int j = i + 1; j < N; j++) {
					if ((mask & (1 << i)) && (mask & (1 << j)))
						scores[mask] += a[i][j];
				}
			}
		}
	}

	void rec(int pos, ll score, int mask, int group) {
		if (pos == (int) rem.size()) {
			s_max(dp[mask], score + scores[group]);
			return;
		}
		rec(pos + 1, score, mask ^ (1 << rem[pos]), group ^ (1 << rem[pos]));
		rec(pos + 1, score, mask, group);
	}
};

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	TaskU solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
	return 0;
}
