Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! 

Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position. 

Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.

An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.


-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.

The first line of each test case contains integer $n$ ($1 \leq n \leq 2 \cdot 10^5$)  — the length of the given permutation.

The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ ($1 \leq a_{i} \leq n$)  — the initial permutation.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.


-----Example-----
Input
2
5
1 2 3 4 5
7
3 2 4 5 1 6 7

Output
0
2



-----Note-----

In the first permutation, it is already sorted so no exchanges are needed.

It can be shown that you need at least $2$ exchanges to sort the second permutation.

$[3, 2, 4, 5, 1, 6, 7]$

Perform special exchange on range ($1, 5$)

$[4, 1, 2, 3, 5, 6, 7]$

Perform special exchange on range ($1, 4$)

$[1, 2, 3, 4, 5, 6, 7]$

Difficulty: MEDIUM
Tags: Mathematics

Constructive algorithms

Starter code:

Solutions:
import math as mt
for x in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	tmp = -1
	flag = 1
	for i in range(n):
		if l[i] != i + 1:
			ans += 1
			if tmp != -1 and i > tmp + 1:
				flag = 0
			tmp = i
	if ans == 0:
		print(0)
	else:
		print(2 - flag)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
for _ in range(II()):
	n = II()
	aa = [0] + LI()
	ans = 0
	for i in range(n):
		if i == aa[i] and i + 1 != aa[i + 1]:
			ans += 1
	print(min(2, ans))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	is_sorted = True
	for i in range(1, n):
		if a[i] < a[i - 1]:
			is_sorted = False
			break
	if is_sorted:
		print(0)
	else:
		all_incorrect = True
		for i in range(n):
			if a[i] == i + 1:
				all_incorrect = False
				break
		if all_incorrect:
			print(1)
		else:
			i = 0
			while a[i] == i + 1:
				i += 1
			j = n - 1
			while a[j] == j + 1:
				j -= 1
			all_incorrect = True
			for k in range(i, j + 1):
				if a[k] == k + 1:
					all_incorrect = False
					break
			if all_incorrect:
				print(1)
			else:
				print(2)


from itertools import groupby

def solve(ar, n):
	pos = [ar[i] == i + 1 for i in range(n)]
	cnt = [key for (key, groups) in groupby(pos)]
	cnt = cnt.count(False)
	if cnt == 0:
		print(0)
	elif cnt == 1:
		print(1)
	else:
		print(2)

def read():
	t = int(input())
	for i in range(t):
		n = int(input())
		ar = list(map(int, input().strip().split()))
		solve(ar, n)
read()


import sys
input = sys.stdin.readline
for z in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	s = 1
	c = 0
	for i in range(n):
		if i + 1 != p[i]:
			if s:
				s = 0
				c += 1
		else:
			s = 1
	print(min(2, c))


T = int(input())
for i in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
		continue
	strt = True
	count = 0
	for i in range(n):
		if strt and i + 1 != a[i]:
			strt = False
		if not strt and i + 1 == a[i]:
			count += 1
	end = True
	for i in range(n - 1, -1, -1):
		if end and i + 1 == a[i]:
			count -= 1
		else:
			break
	if count == 0:
		print(1)
	else:
		print(2)


for w in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	m = -1
	if a == sorted(a):
		print(0)
	else:
		d = {}
		for i in range(n):
			d[a[i]] = i
		for i in range(n):
			if a[i] != i + 1:
				break
		for j in reversed(range(n)):
			if a[j] != j + 1:
				break
		c = 0
		for k in range(i, j + 1):
			if a[k] == k + 1:
				c = 1
				break
		if c == 1:
			print(2)
		else:
			print(1)


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = list(map(int, list(next_line)))
		elif input_format == 5:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c

def mapl(iterable, format=0):
	if format == 0:
		return list(map(int, iterable))
	elif format == 1:
		return list(map(str, iterable))
	elif format == 2:
		return list(map(list, iterable))

def solve():
	n = input(11)
	a = input(1)
	if a == sorted(a):
		out(0)
	else:
		e = []
		for (i, j) in enu(a):
			if i + 1 == j:
				e.append(1)
			else:
				e.append(0)
		log(e)
		f0 = 0
		f1 = 0
		for i in e:
			if i == 0:
				if f0 and f1:
					break
				f0 = 1
			elif f0:
				f1 = 1
		else:
			out(1)
			return
		out(2)
	return
for i in range(input(11)):
	solve()


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	if a == list(range(1, n + 1)):
		print(0)
		continue
	(l, r) = (0, n - 1)
	for i in range(n):
		if a[i] == i + 1:
			l = i + 1
		else:
			break
	for i in range(n - 1, -1, -1):
		if a[i] == i + 1:
			r = i - 1
		else:
			break
	ok = 1
	for i in range(l, r + 1):
		if a[i] == i + 1:
			ok = 0
			break
	print(1 if ok else 2)


import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	flag = 0
	c = 0
	for j in range(n):
		if a[j] != j + 1:
			flag = 1
		elif flag == 1:
			flag = 0
			c += 1
	if flag == 1:
		c += 1
	if c < 2:
		print(c)
	else:
		print(2)


from sys import stdin, stdout
import math, queue, heapq
fastinput = stdin.readline
fastout = stdout.write
t = int(fastinput())
while t:
	t -= 1
	n = int(fastinput())
	a = list(map(int, fastinput().split()))
	ans = 0
	mem = 1
	for i in range(1, n + 1):
		if a[i - 1] == i:
			mem = 1
		else:
			if mem == 1:
				ans += 1
			mem = 0
		if ans >= 2:
			break
	print(min(ans, 2))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))[:n]
	g = []
	(a, b) = (0, 0)
	for i in range(n):
		if i + 1 == l[i]:
			g.append(0)
		else:
			g.append(1)
	for i in range(n):
		if g[i] == 1:
			a = i
			break
	for i in range(n - 1, 0, -1):
		if g[i] == 1:
			b = i
			break
	if len(g[a:b]) == 0:
		print(0)
	elif g[a:b].count(0) == 0:
		print(1)
	else:
		print(2)


import time, math as mt, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return
mod = 10 ** 9 + 7

def solve():
	n = II()
	li = L()
	pos = []
	if sorted(li) == li:
		P(0)
	else:
		start = 0
		for i in range(n):
			if li[i] == i + 1:
				start += 1
			else:
				break
		end = 0
		for i in range(n - 1, -1, -1):
			if li[i] == i + 1:
				end += 1
			else:
				break
		for i in range(start, n - end):
			if li[i] == i + 1:
				P(2)
				break
		else:
			P(1)
t = II()
for i in range(t):
	solve()


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().rstrip().split(' ')))
	firstFew = n - 1
	for i in range(n):
		if arr[i] != i + 1:
			firstFew = i
			break
	if firstFew == n - 1:
		print(0)
		continue
	lastFew = n - i
	for i in range(n):
		if arr[n - i - 1] != n - i:
			lastFew = n - i - 1
			break
	correctlyPlaced = 0
	for i in range(firstFew, lastFew):
		if arr[i] == i + 1:
			correctlyPlaced += 1
			break
	if correctlyPlaced > 0:
		print(2)
	else:
		print(1)


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heapreplace, heappushpop

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
res = ['YES', 'NO']
test_case = ii()
while test_case:
	test_case -= 1
	n = ii()
	a = li()
	c = []
	for i in range(n):
		if a[i] - 1 == i:
			c.append(i)
	if len(c) == n:
		ans = 0
	elif not c:
		ans = 1
	else:
		ans = 2
		j = 0
		for i in c:
			if i != j:
				break
			j += 1
		k = n - 1
		for i in c[::-1]:
			if i != k:
				break
			k -= 1
			j += 1
		if j == len(c):
			ans = 1
	print(ans)


from collections import Counter
import math
import sys
from bisect import bisect, bisect_left, bisect_right

def input():
	return sys.stdin.readline().strip()

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def mod():
	return 10 ** 9 + 7
for i in range(INT()):
	n = INT()
	arr = LIST()
	ans = []
	for i in range(n):
		if arr[i] != i + 1:
			ans.append(i)
	if len(ans) == 0:
		print(0)
	elif ans[-1] - ans[0] + 1 == len(ans):
		print(1)
	else:
		print(2)


t = int(input())
for q in range(t):
	n = int(input())
	li = list(map(int, input().split(' ', n)[:n]))
	if sorted(li) == li:
		print(0)
	else:
		s = 0
		st = 0
		while st < n:
			if li[st] != st + 1:
				break
			st += 1
		en = n - 1
		while en >= 0:
			if li[en] != en + 1:
				break
			en -= 1
		for i in range(st, en + 1):
			if li[i] == i + 1:
				s = 1
				break
		if s == 1:
			print(2)
		else:
			print(1)


import sys, math
import io, os
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
mod = int(1000000000.0) + 7
for i in range(int(data())):
	n = int(data())
	a = mdata()
	(s, e) = (-1, -1)
	cnt = 0
	for i in range(n):
		if a[i] != i + 1:
			if s == -1:
				s = i
			e = i
			cnt += 1
	if s == -1:
		out(0)
	elif e - s + 1 == cnt:
		out(1)
	else:
		out(2)


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(*a,) = map(int, input().split())
	b = c = d = 0
	p = -1
	for i in range(n):
		if a[i] == i + 1:
			b = 1
		else:
			if p == i - 1 or p == -1:
				p = i
			else:
				d = 1
			c = 1
	if b and c:
		if not d:
			print(1)
		else:
			print(2)
	elif b:
		print(0)
	else:
		print(1)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	start = 0
	end = n - 1
	while start < n:
		if l[start] == start + 1:
			start += 1
		else:
			break
	while end >= 0:
		if l[end] == end + 1:
			end -= 1
		else:
			break
	if start > end:
		print(0)
	else:
		cando = 1
		for j in range(start, end + 1):
			if l[j] == j + 1:
				print(2)
				cando = 0
				break
		if cando == 1:
			print(1)


for _ in ' ' * int(input()):
	a = int(input())
	b = list(map(int, input().split()))
	s = t = 0
	for i in range(a):
		if b[i] != i + 1:
			if s == 0:
				s += 1
			elif s == 1 and t:
				s += 1
				break
		t = b[i] == i + 1
	print(s)


for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	l = 0
	check = True
	for i in range(n):
		if a[i] == i + 1:
			cnt += 1
			if check:
				l += 1
		else:
			check = False
	if cnt == n:
		print(0)
	else:
		r = 0
		check = True
		for i in range(n - 1, -1, -1):
			if a[i] == i + 1:
				if check:
					r += 1
			else:
				check = False
		if l + r == cnt:
			print(1)
		else:
			print(2)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	x = arr[:]
	x.sort()
	pre = [0]
	for i in range(n - 1):
		if x[i] != arr[i]:
			pre += [pre[-1] + 1]
		else:
			pre += [pre[-1]]
	post = [0]
	for i in range(n - 1, 0, -1):
		if x[i] != arr[i]:
			post += [post[-1] + 1]
		else:
			post += [post[-1]]
	post.reverse()
	kind = 0
	for i in range(n):
		if pre[i] > 0 and post[i] > 0 and (arr[i] == x[i]):
			kind = 2
			break
		elif pre[i] > 0 or post[i] > 0:
			kind = 1
	print(kind)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = a.copy()
	b.sort()
	if a == b:
		print(0)
	else:
		(k1, k2) = (0, n - 1)
		while True:
			if a[k1] != k1 + 1:
				break
			else:
				k1 += 1
		while True:
			if a[k2] != k2 + 1:
				break
			else:
				k2 -= 1
		f = True
		for i in range(k1, k2 + 1):
			if i + 1 == a[i]:
				f = False
				break
		if f == True:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if sorted(a) == a:
		print(0)
		continue
	l = 0
	r = n - 1
	ll = 1
	rr = n
	while l < len(a) and a[l] == ll:
		ll += 1
		l += 1
	while r > -1 and a[r] == rr:
		rr -= 1
		r -= 1
	flag = 0
	for i in range(l, r + 1):
		if a[i] == i + 1:
			flag = 1
	print(1 if not flag else 2)


def check(A):
	n = len(A)
	for i in range(1, n):
		if A[i] - A[i - 1] >= 2:
			return 1
	return 0
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	C = []
	for i in range(n):
		C.append(A[i])
	C.sort()
	if C == A:
		print(0)
		continue
	pospre = []
	for i in range(n):
		if A[i] != i + 1:
			pospre.append(i + 1)
	possuf = []
	A = A[::-1]
	for i in range(n):
		if A[i] != i + 1:
			possuf.append(i + 1)
	a = check(pospre)
	if a == 1:
		print(2)
	else:
		print(1)


from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
import io
input = lambda : sys.stdin.readline().rstrip('\r\n')
for t in range(int(input())):
	n = int(input())
	arr = [0] + list(map(int, input().split()))
	tr = 0
	for i in range(n + 1):
		if tr == 0 and arr[i] != i:
			tr = 1
		elif tr == 1 and arr[i] == i:
			tr = 2
		elif tr == 2 and arr[i] != i:
			tr = 3
	if tr == 0:
		print(0)
	elif tr == 1 or tr == 2:
		print(1)
	else:
		print(2)


import sys
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
for _ in range(ii1()):
	n = ii1()
	arr = iia()
	if arr == sorted(arr):
		print(0)
	else:
		flag = False
		for (idx, val) in enumerate(arr):
			if idx + 1 == val:
				flag = True
				break
		if flag == False:
			print(1)
		else:
			i = 0
			while i < n:
				if i + 1 == arr[i]:
					i += 1
				else:
					break
			j = i
			while j < n:
				if j + 1 != arr[j]:
					j += 1
				else:
					break
			if j == n:
				print(1)
			else:
				k = j
				while k < n:
					if k + 1 == arr[k]:
						k += 1
					else:
						break
				if k == n:
					print(1)
				else:
					print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))

	def check():
		suffix_end = n
		for j in range(n - 1, -1, -1):
			if j + 1 == arr[j]:
				suffix_end = j
			else:
				break
		if suffix_end == 0:
			return 0
		prefix_end = 0
		for i in range(n):
			if i + 1 == arr[i]:
				prefix_end = i
			else:
				break
		for i in range(prefix_end + 1, suffix_end):
			if i + 1 == arr[i]:
				return 2
		return 1
	print(check())


for _ in range(int(input())):
	n = int(input())
	lst = [int(x) for x in input().split()]
	k = 0
	if lst[0] == 1:
		prev = True
	else:
		(k, prev) = (1, False)
	for i in range(1, n):
		if lst[i] == i + 1:
			prev = True
		else:
			if prev:
				k += 1
			prev = False
	print(min(k, 2))


t = int(input())
for test_case in range(1, t + 1):
	n = int(input())
	l = list(map(int, input().split()))
	finished = False
	l_sorted = 0
	while l_sorted < n:
		if l[l_sorted] == l_sorted + 1:
			l_sorted += 1
		else:
			break
	r_sorted = n - 1
	while r_sorted > 0:
		if l[r_sorted] == r_sorted + 1:
			r_sorted -= 1
		else:
			break
	if l_sorted == n:
		print('0')
	else:
		well_placed = 0
		for i in range(l_sorted, r_sorted + 1):
			if l[i] == i + 1:
				well_placed += 1
		if well_placed == 0:
			print('1')
		else:
			print('2')


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	p = 0
	ans = []
	for i in range(n):
		if ar[i] != i + 1:
			ans.append(i + 1)
	if len(ans) == 0:
		print(0)
	elif max(ans) - min(ans) + 1 == len(ans):
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	l = []
	for i in range(1, n + 1):
		if i == a[i - 1]:
			continue
		else:
			c += 1
			l.append(i)
	f = 0
	for i in range(1, len(l)):
		if l[i] - l[i - 1] > 1:
			f = 1
			break
	if c == 0:
		print(0)
	elif f == 0:
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	j = 0
	k = n - 1
	count = 0
	x = []
	for b in range(len(a)):
		x.append(a[b])
	x.sort()
	if a == x:
		print(0)
	else:
		while a[j] == j + 1:
			a[j] = 0
			j += 1
		while a[k] == k + 1:
			a[k] = 0
			k -= 1
		for m in range(len(a)):
			if a[m] != m + 1:
				count += 1
		if count == n:
			print(1)
		else:
			print(2)


t = int(input())
for k in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a += [n + 1]
	cnt = 0
	c = [True] * (n + 1)
	for i in range(n):
		if a[i] != i + 1:
			c[i] = False
	for i in range(n):
		if not c[i] and c[i + 1]:
			cnt += 1
	print(min(cnt, 2))


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	c = 0
	tilt = False
	for i in range(n):
		(ind, val) = (i + 1, arr[i])
		if ind != val:
			if not tilt:
				c = c + 1
				tilt = True
		elif tilt:
			tilt = False
	if c == 0:
		ans = 0
	elif c == 1:
		ans = 1
	else:
		ans = 2
	print(ans)


count = int(input())
for i in range(count):
	trash = input()
	perm_g = map(int, input().split())
	previous = True
	changes = 0
	for (num, elem) in enumerate(perm_g):
		now = num + 1 == elem
		if now != previous:
			changes += 1
		previous = now
	if changes == 0:
		print(0)
	elif changes < 3:
		print(1)
	else:
		print(2)


def solve():
	x = int(input())
	s = list(map(int, input().split()))
	if s == sorted(s):
		print(0)
		return
	ps = 1
	for n in range(x):
		if s[n] == n + 1 and 0 < n < x - 1:
			ps = 0
			break
	if ps:
		print(1)
		return
	n = 0
	while s[n] == n + 1:
		n += 1
	k = x - 1
	while s[k] == k + 1:
		k -= 1
	for a in range(n, k + 1):
		if s[a] == a + 1:
			print(2)
			return
	print(1)
for n in range(int(input())):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	flag = 0
	for i in range(n):
		if l[i] != i + 1:
			flag = 1
			break
	if flag == 0:
		print(0)
	else:
		(f1, f2, flag) = (0, 0, 0)
		for i in range(n):
			if l[i] != i + 1:
				if f2 == 1:
					flag = 1
					break
				f1 = 1
			elif f1 == 1:
				f2 = 1
		if flag == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	arr = []
	flag = True
	for i in range(0, n):
		arr.append(i + 1 - l[i])
		if i + 1 != l[i]:
			flag = False
	for i in (0, -1):
		while arr and arr[i] == 0:
			arr.pop(i)
	if flag:
		print(0)
	elif 0 in arr:
		print(2)
	else:
		print(1)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	n = int(inp())
	a = lis()
	cnt = 0
	l = 0
	while l < n and a[l] == l + 1:
		l += 1
	end = n - 1
	while end >= 0 and a[end] == end + 1:
		end -= 1
	if l >= end:
		print(0)
		return
	for i in range(l, end + 1):
		if a[i] == i + 1:
			cnt += 1
	if cnt == 0:
		print(1)
	else:
		print(2)
testcase(int(inp()))


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n,) = I()
	l = I()
	cc = []
	for i in range(n):
		if i + 1 != l[i]:
			cc.append(i + 1)
	k = len(cc)
	if k != 0:
		x = 2
		if cc[k - 1] - cc[0] + 1 == k:
			x = 1
		print(x)
	else:
		print(0)


from __future__ import division, print_function
import itertools, os, sys, threading
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from math import gcd
from bisect import bisect
from random import randrange
input = lambda : sys.stdin.readline().rstrip('\r\n')
read = lambda : list(map(int, input().strip().split(' ')))

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = read()
		s = ''
		for i in range(n):
			s += ['0', '1'][arr[i] != i + 1]
		s = sum([1 for i in s.strip('0').split('0') if '1' in i])
		if not s:
			print(0)
		elif s > 1:
			print(2)
		else:
			print(1)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	maxa = a[-1]
	flag = 0
	for i in range(1, n + 1):
		if i != a[i - 1]:
			flag = 1
			break
	if flag == 1:
		cnt = 0
		i = n - 2
		while i >= 0:
			if a[i] > maxa:
				if a[i] == i + 1:
					cnt += 1
			else:
				maxa = a[i]
			i -= 1
		if cnt > 0:
			print(2)
		else:
			print(1)
	else:
		print(0)


import collections
t = int(input())
import math
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr1 = sorted(arr)
	if arr == arr1:
		print(0)
		continue
	stage = 0
	ans = 1
	for j in range(len(arr)):
		if arr[j] == j + 1:
			if stage == 1:
				stage = 2
		elif stage == 0:
			stage = 1
		elif stage == 2:
			ans = 2
			break
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	c = []
	for j in b:
		c.append(j)
	c.sort()
	if b == c:
		print(0)
	else:
		j = 0
		f = 0
		while j < n:
			if b[j] == j + 1:
				pass
			else:
				q = j
				break
			j += 1
		j = n - 1
		while j >= 0:
			if b[j] == j + 1:
				pass
			else:
				r = j
				break
			j += -1
		j = q
		while j <= r:
			if b[j] == j + 1:
				f = 1
				break
			j += 1
		if f == 1:
			print(2)
		else:
			print(1)


for s in [*open(0)][2::2]:
	l = list(map(int, s.split()))
	c = 0
	s = 1
	for i in range(len(l)):
		if i + 1 != l[i]:
			if s:
				c += 1
				s = 0
		else:
			s = 1
	print(min(2, c))


def solve():
	n = int(input())
	a = list(map(int, input().split(' ')))
	notSorted = False
	for i in range(1, n):
		if a[i - 1] > a[i]:
			notSorted = True
	if notSorted == False:
		print(0)
		return
	ii = n - 1
	jj = 0
	while jj < n:
		if a[jj] != jj + 1:
			break
		jj += 1
	while ii >= jj:
		if a[ii] != ii + 1:
			break
		ii -= 1
	for i in range(jj, ii + 1):
		if a[i] == i + 1:
			print(2)
			return
	print(1)
t = int(input())
for i in range(t):
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	sorteda = [i for i in a]
	sorteda.sort()
	acheck = [1 if a[i] == sorteda[i] else 0 for i in range(n)]
	a1check = [i for i in acheck]
	a1check.reverse()
	if a == sorteda:
		print(0)
	elif 1 not in acheck:
		print(1)
	elif n == 2:
		print(1)
	else:
		for i in range(n):
			if acheck[i] == 0:
				s = i
				break
		for i in range(n):
			if a1check[i] == 0:
				end = n - i
				break
		a2 = acheck[s:end]
		if 1 in a2:
			print(2)
		else:
			print(1)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(cont, ant) = (0, 0)
	for i in range(1, n + 1):
		if a[i - 1] == i:
			ant = 0
		elif ant == 0:
			ant = 1
			cont += 1
	print(min(cont, 2))


from heapq import heappop, heappush

def main():
	for t in range(int(input())):
		n = int(input())
		l = [int(j) for j in input().split()]
		i = 0
		seen = False
		ans = 0
		wps = n
		wpe = -1
		for i in range(n):
			if l[i] - 1 != i:
				wps = min(wps, i)
				wpe = max(wpe, i)
		ans = 0
		if wps != n:
			ans = 1
			for i in range(n):
				if i == l[i] - 1:
					if wps < i < wpe:
						ans = 2
		print(ans)
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	n = int(input())
	list1 = list(map(int, input().split()))
	if sorted(list1) == list1:
		print(0)
	elif list1[0] == 1 and list1[n - 1] == n:
		flag = 0
		i = 1
		j = n - 2
		while i < n:
			if list1[i] != i + 1:
				strt = i
				break
			i += 1
		while j >= 0:
			if list1[j] != j + 1:
				end = j
				break
			j -= 1
		for i in range(strt, end + 1):
			if list1[i] == i + 1:
				flag = 1
				break
		if flag == 1:
			print('2')
		else:
			print('1')
	elif list1[0] == 1:
		flag = 0
		i = 1
		while i < n:
			if list1[i] != i + 1:
				strt = i
				break
			i += 1
		for i in range(strt, n):
			if list1[i] == i + 1:
				flag = 1
				break
		if flag == 1:
			print('2')
		else:
			print('1')
	elif list1[n - 1] == n:
		flag = 0
		j = n - 1
		strt = 0
		while j >= 0:
			if list1[j] != j + 1:
				strt = j
				break
			j -= 1
		for i in range(strt, -1, -1):
			if list1[i] == i + 1:
				flag = 1
				break
		if flag == 1:
			print('2')
		else:
			print('1')
	else:
		flag = 0
		for i in range(len(list1)):
			if list1[i] == i + 1:
				flag = 1
		if flag == 0:
			print('1')
		else:
			print('2')


t = int(input())
for ii in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	unfixSeg = 0
	end = False
	for i in range(n):
		if i + 1 != l[i]:
			if not end:
				end = True
		elif end:
			unfixSeg += 1
			end = False
	if end:
		unfixSeg += 1
	if unfixSeg == 0:
		print(0)
	elif unfixSeg == 1:
		print(1)
	else:
		print(2)


from sys import stdin
input = stdin.readline

def answer():
	i = 0
	while i < n and a[i] == i + 1:
		i += 1
	if i == n:
		return 0
	while i < n and a[i] != i + 1:
		i += 1
	if i == n:
		return 1
	while i < n and a[i] == i + 1:
		i += 1
	if i == n:
		return 1
	return 2
for T in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	print(answer())


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	j = n - 1
	while i < j:
		if a[i] == i + 1:
			i += 1
		elif a[j] == j + 1:
			j -= 1
		elif i == j:
			break
		else:
			break
	p = 0
	q = 0
	if i == j:
		print(0)
		continue
	for x in range(i, j + 1):
		if a[x] == x + 1:
			p += 1
		else:
			q += 1
	if p == 0:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	o = l.copy()
	o.sort()
	if l == o:
		print(0)
		continue
	i = 0
	e = []
	s = set()
	while i < len(l):
		if l[i] == i + 1:
			e.append(i + 1)
			s.add(i + 1)
		i = i + 1
	if len(e) == 0:
		print(1)
		continue
	if e[0] > 1 and e[-1] < n:
		print(2)
		continue
	f = 0
	ix = 1
	while ix <= n and f == 0:
		if ix in s:
			s.remove(ix)
			ix = ix + 1
		else:
			f = 1
	f = 0
	ix = n
	while ix >= 1 and f == 0:
		if ix in s:
			s.remove(ix)
			ix = ix - 1
		else:
			f = 1
	if len(s) == 0:
		f = 0
	else:
		f = 1
	if f == 1:
		print(2)
	else:
		print(1)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	all_rev = True
	for i in range(n):
		if a[i] == i + 1:
			all_rev = False
			break
	if a == sorted(a):
		print(0)
	else:
		ct = 0
		i = 0
		while i < n:
			j = i + 1
			if a[i] != i + 1:
				while j < n and j != a[j] - 1:
					j += 1
				ct += 1
			i = j
		if ct == 1:
			print(1)
		else:
			print(2)


import math

def gcd(a, b):
	return a if b == 0 else gcd(b, a % b)

def lcm(a, b):
	return a * b // gcd(a, b)

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	id = -1
	ld = -1
	cnt = 0
	for i in range(n - 1, -1, -1):
		if a[i] != i + 1:
			id = i
			break
	for i in range(0, id):
		if a[i] != i + 1:
			ld = i
			break
	for i in range(ld, id + 1):
		if a[i] == i + 1:
			cnt += 1
	ans = 0
	if id == -1:
		ans = 0
	elif cnt == 0:
		ans = 1
	else:
		ans = 2
	print(ans)
test = 1
test = int(input())
for _ in range(test):
	solve()


import math
T = int(input())
for _ in range(T):
	n = int(input())
	arr = [int(x) for x in input().split(' ')]
	beg = None
	end = None
	index = 0
	while index < len(arr) - 1:
		if index + 1 != arr[index]:
			beg = index
			break
		index = index + 1
	if beg is None:
		print(0)
		continue
	index = len(arr) - 1
	while index > 0:
		if index + 1 != arr[index]:
			end = index
			break
		index = index - 1
	correct = False
	for i in range(beg + 1, end):
		if arr[i] == i + 1:
			correct = True
			break
	if correct == False:
		print(1)
		continue
	print(2)


import math
n = int(input())
for _ in range(n):
	a = int(input())
	lis = list(map(int, input().split()))
	lis2 = sorted(lis)
	if lis == lis2:
		print('0')
	else:
		for i in range(1, a + 1):
			if lis[a - i] != lis2[a - i]:
				break
		c = 0
		for z in range(a):
			if lis[z] != lis2[z]:
				break
		for j in range(z, a - i + 1):
			if lis[j] == lis2[j]:
				c += 1
		if c == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	flag = False
	x = 0
	y = n - 1
	while x < n and a[x] == x + 1:
		x += 1
	while y >= 0 and a[y] == y + 1:
		y -= 1
	if x > y:
		print(0)
	else:
		for i in range(x, y + 1):
			if a[i] == i + 1:
				flag = True
				break
		if flag:
			print(2)
		else:
			print(1)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))
ilelec = lambda : map(int1, input().split())
alelec = lambda : list(map(int1, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	N = int(input())
	A = alele()
	m = [0] * N
	for i in range(N):
		if A[i] == i + 1:
			m[i] = 1
	c = m.count(1)
	if c == N:
		print(0)
	elif c == 0:
		print(1)
	else:
		l = 0
		while l < N and m[l] == 1:
			l += 1
		r = N - 1
		while r >= 0 and m[r] == 1:
			r -= 1
		if 1 not in m[l:r + 1]:
			print(1)
		else:
			print(2)


import math
from decimal import Decimal
import heapq
import copy
import heapq
from collections import deque

def na():
	n = int(input())
	b = [int(x) for x in input().split()]
	return (n, b)

def nab():
	n = int(input())
	b = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	return (n, b, c)

def dv():
	(n, m) = map(int, input().split())
	return (n, m)

def da():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	return (n, m, a)

def dva():
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	return (n, m, b)

def eratosthenes(n):
	sieve = list(range(n + 1))
	for i in sieve:
		if i > 1:
			for j in range(i + i, len(sieve), i):
				sieve[j] = 0
	return sorted(set(sieve))

def lol(lst, k):
	k = k % len(lst)
	ret = [0] * len(lst)
	for i in range(len(lst)):
		if i + k < len(lst) and i + k >= 0:
			ret[i] = lst[i + k]
		if i + k >= len(lst):
			ret[i] = lst[i + k - len(lst)]
		if i + k < 0:
			ret[i] = lst[i + k + len(lst)]
	return ret

def nm():
	n = int(input())
	b = [int(x) for x in input().split()]
	m = int(input())
	c = [int(x) for x in input().split()]
	return (n, b, m, c)

def dvs():
	n = int(input())
	m = int(input())
	return (n, m)

def fact(n):
	tc = []
	ans = {}
	d = 2
	while d * d <= n:
		if n % d == 0:
			tc.append(d)
			n //= d
		else:
			d += 1
	if n > 1:
		tc.append(n)
	for i in tc:
		ans[i] = ans.get(i, 0) + 1
	return ans

def how_many(l, r, c):
	m = (l + r) // 2
	if r - l == 1:
		if s[l] == c:
			return 0
		else:
			return 1
	d = s[l:m]
	k1 = (r - l) // 2 - s[l:m].count(c) + how_many(m, r, chr(ord(c) + 1))
	k2 = (r - l) // 2 - s[m:r].count(c) + how_many(l, m, chr(ord(c) + 1))
	return min(k1, k2)
for _ in range(int(input())):
	(n, a) = na()
	k = 0
	k1 = 0
	b = [0] * n
	for i in range(n):
		if a[i] == i + 1:
			b[i] = 1
			k += 1
		if a[i] != i + 1:
			k1 += 1
	if k == n:
		print(0)
		continue
	if k1 == n:
		print(1)
		continue
	lst = b[0]
	k = 0
	k0 = 0
	k1 = 0
	if lst == 0:
		k0 += 1
	for i in range(1, n):
		if b[i] != lst:
			k += 1
			if b[i] == 1:
				k1 += 1
			else:
				k0 += 1
			lst = b[i]
	if k == 2 and k0 == 2:
		print(2)
	elif k == 2 and k0 == 1:
		print(1)
	elif k == 1:
		print(1)
	else:
		print(2)


t = int(input())
ans = []
for _ in range(t):
	n = int(input())
	arr = input().split(' ')
	for i in range(n):
		arr[i] = int(arr[i])
	bp = n - 1
	while bp >= 0:
		if arr[bp] == bp + 1:
			bp -= 1
			continue
		else:
			break
		bp -= 1
	if bp == -1:
		ans.append(0)
		continue
	i = 0
	curr = 0
	while i < n:
		if curr == 0 and arr[i] == i + 1:
			i += 1
			continue
		elif curr == 0 and arr[i] != i + 1:
			curr += 1
			i += 1
			continue
		elif curr == 1 and i >= bp:
			break
		elif curr == 1 and arr[i] == i + 1:
			curr += 1
			break
		i += 1
	ans.append(curr)
for i in range(len(ans)):
	print(ans[i])


T = int(input())

def checkOrder(i, j, arr):
	for k in range(0, len(arr)):
		if arr[k] == i + k + 1:
			return 0
	return 1

def getSubarrStart(arr):
	for i in range(0, len(arr)):
		if arr[i] != i + 1:
			return i
	return -1

def getSubarrEnd(arr):
	for i in range(len(arr) - 1, -1, -1):
		if arr[i] != i + 1:
			return i
	return -1

def solve(arr):
	i = getSubarrStart(arr)
	j = getSubarrEnd(arr)
	if i == -1:
		return 0
	sub = arr[i:j]
	if checkOrder(i, j, sub) == 0:
		return 2
	return 1
while T > 0:
	n = int(input())
	arr = [int(el) for el in input().split(' ')]
	print(solve(arr))
	T -= 1


import sys
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

def find(x):
	ans = []
	for i in range(1, int(x ** 0.5) + 1):
		if x % i:
			continue
		ans.append(i)
		ans.append(x // i)
	return ans

def solve():
	(n,) = I()
	a = I()
	if a == sorted(a):
		print(0)
		return
	else:
		ok = 0
		idx = -1
		i = 0
		while i < n and a[i] == i + 1:
			i += 1
		j = n - 1
		while j >= 0 and a[j] == j + 1:
			j -= 1
		for k in range(i, j + 1):
			if a[k] == k + 1:
				ok = 1
		print(1 + ok)
(t,) = I()
while t:
	t -= 1
	solve()


for t in range(int(input())):
	n = int(input())
	(*a,) = map(int, input().split())
	s = list(sorted(a))
	(l, r) = (0, n - 1)
	while l < n and a[l] == s[l]:
		l += 1
	while r >= 0 and a[r] == s[r]:
		r -= 1
	if l < r:
		r += 1
		ans = 1
		for i in range(l, r):
			if a[i] == s[i]:
				ans = 2
				break
		print(ans)
	else:
		print(0)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	prev = -1
	mixed = False
	for i in range(n):
		if a[i] != i + 1:
			if prev < 0 or prev + 1 == i:
				prev = i
			else:
				mixed = True
	if prev == -1:
		print(0)
	elif mixed:
		print(2)
	else:
		print(1)


def solve(x):
	i = 0
	res = 0
	while i < len(x):
		if x[i] != i + 1:
			res += 1
			while i < len(x) and x[i] != i + 1:
				i += 1
		else:
			i += 1
	if res < 2:
		return res
	else:
		return 2
tests = int(input())
for _ in range(tests):
	n = int(input())
	arr = list(map(lambda x: int(x), input().split(' ')))
	print(solve(arr))


import sys
input = sys.stdin.readline
T = int(input())
for testcase in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	sm = 0
	mi = n
	ma = -1
	for i in range(n):
		if i + 1 == a[i]:
			sm += 1
			mi = min(mi, i)
			ma = max(ma, i)
	if sm == n:
		print(0)
	elif sm == 0:
		print(1)
	else:
		cnt = 0
		for i in range(n):
			if i + 1 != a[i]:
				break
			cnt += 1
		for i in range(n - 1, -1, -1):
			if i + 1 != a[i]:
				break
			cnt += 1
		if cnt == sm:
			print(1)
		else:
			print(2)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	le = 0
	li = []
	for i in range(n):
		if ar[i] != i + 1:
			le += 1
			li.append(i)
	if le == 0:
		print(0)
	elif le == 1:
		print(1)
	else:
		flag = True
		for i in range(1, le):
			if li[i] - li[i - 1] != 1:
				flag = False
				break
		if flag:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	l = input().split()
	for j in range(0, n):
		if int(l[j]) != j + 1:
			break
	if j == n - 1:
		print(0)
	else:
		a = j
		b = n - 1
		j = n - 1
		for j in range(n - 1, -1, -1):
			if int(l[j]) != j + 1:
				b = j
				break
		for j in range(a, b + 1):
			if int(l[j]) == j + 1:
				break
		if j == b:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	xs = [int(x) for x in input().split()]
	all_wrong = True
	all_right = True
	streak = False
	streaks = 0
	for (i, x) in enumerate(xs):
		if x == i + 1:
			if streak:
				streak = False
		elif not streak:
			streak = True
			streaks += 1
			if streaks == 2:
				break
	else:
		print(streaks)
		continue
	print(2)


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	i = 0
	while i != n and arr[i] == i + 1:
		i += 1
	j = n - 1
	while j != -1 and arr[j] == j + 1:
		j -= 1
	cou = 0
	for x in range(i, j + 1):
		if arr[x] == x + 1:
			cou = 1
			break
	if i == n:
		print(0)
	elif cou:
		print(2)
	else:
		print(1)


for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	(i, j) = (0, n - 1)
	while i < n and i + 1 == lst[i]:
		i += 1
	while j > -1 and j + 1 == lst[j]:
		j -= 1
	if i > j:
		print(0)
	else:
		c = 0
		for p in range(i, j + 1):
			if p + 1 == lst[p]:
				c += 1
		if c == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = [0] + a
	k = []
	check1 = 0
	check2 = 0
	l = 0
	for i in range(1, n + 1):
		if a[i] != i:
			check1 = 1
		else:
			l += 1
			k.append(i)
	if check1 == 0:
		print(0)
	else:
		if l > 0:
			if k[0] == 1 and k[l - 1] == n:
				for i in range(1, l):
					if k[i] - k[i - 1] > 1:
						j = i
						break
				for i in range(j + 1, l):
					if k[i] - k[i - 1] > 1:
						check2 = 1
						break
			elif k[0] == 1 or k[l - 1] == n:
				for i in range(1, l):
					if k[i] - k[i - 1] > 1:
						check2 = 1
						break
			else:
				check2 = 1
		if check2 == 0:
			print(1)
		else:
			print(2)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
testcases = int(input())
for j in range(testcases):
	n = int(input())
	perms = list(map(int, input().split()))
	indexed = 0
	dict1 = {}
	indices = []
	for s in range(n):
		dict1[s] = 0
	for s in range(n):
		if perms[s] == s + 1:
			indexed += 1
		else:
			indices.append(s)
		dict1[(s + 1 - perms[s]) % n] += 1
	if indexed == n:
		print(0)
	else:
		minsofar = n
		for s in dict1.keys():
			if dict1[s] < minsofar:
				minsofar = dict1[s]
		if indexed == 0:
			print(1)
		else:
			val = abs(indices[-1] - indices[0])
			if val == len(indices) - 1:
				print(1)
			else:
				print(2)


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		ar = inpt()
		a = 0
		b = 0
		ok = False
		for i in range(n):
			if ar[i] == i + 1:
				a += 1
			elif b == 0:
				b += 1
				a = 0
			elif a > 0:
				ok = True
			else:
				b += 1
				a = 0
		if b == 0:
			print(0)
		elif ok:
			print(2)
		else:
			print(1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	f = 0
	cnt = 0
	i = 0
	if b == a:
		print(0)
	else:
		r = n - 1
		l = 0
		c = 0
		while a[r] == r + 1:
			r -= 1
		while a[l] == l + 1:
			l += 1
		for i in range(l, r + 1, 1):
			if a[i] == i + 1:
				c = 1
				break
		if c == 0:
			print(1)
		else:
			print(2)


import math
from collections import deque
import sys
sys.setrecursionlimit(10 ** 4)

def Divisors(n):
	l = []
	i = 2
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
		i = i + 1
	return l

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(n)
	return l

def Factors(n):
	result = []
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			if i == n / i:
				result.append(i)
			else:
				result.append(i)
				result.append(n // i)
	result.append(1)
	return result

def maxSubArraySum(a):
	max_so_far = 0
	max_ending_here = 0
	size = len(a)
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < abs(max_ending_here):
			max_so_far = max_ending_here
	return max_so_far

def longestsubarray(arr, n, k):
	current_count = 0
	max_count = 0
	for i in range(0, n, 1):
		if arr[i] % k != 0:
			current_count += 1
		else:
			current_count = 0
		max_count = max(current_count, max_count)
	return max_count

def main():
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	f = 0
	for i in range(1, n + 1):
		if l[i - 1] != i:
			l1.append(0)
			f = 1
		else:
			l1.append(1)
	if f == 0:
		print(0)
		return
	for i in range(0, n):
		if l1[i] != 1:
			break
	s = i
	for i in range(n - 1, -1, -1):
		if l1[i] != 1:
			break
	p = i
	c = 0
	for i in range(s, p + 1):
		if l1[i] == 1:
			c += 1
	if c == 0:
		print(1)
	else:
		print(2)
t = int(input())
for i in range(0, t):
	main()


t = int(input())
while t:
	t -= 1
	n = int(input())
	lis = list(map(int, input().split()))
	c1 = 0
	for i in range(n):
		if lis[i] != i + 1:
			break
		else:
			c1 += 1
	c2 = 0
	for i in range(n - 1, -1, -1):
		if i + 1 != lis[i]:
			break
		else:
			c2 += 1
	if c1 == n:
		print(0)
	else:
		c = 0
		for i in range(c1, n - 1 - c2):
			if lis[i] == i + 1:
				c += 1
		if c == 0:
			print(1)
		else:
			print(2)


tests = int(input())
for t in range(tests):
	n = int(input())
	ls = list(map(int, input().split()))
	check = True
	res = [0 for _ in range(n)]
	count = 0
	for i in range(n):
		if ls[i] != i + 1:
			check = False
		else:
			res[i] = 1
			count += 1
	if check:
		print(0)
	else:
		for i in range(n):
			if res[i] == 1:
				count -= 1
			else:
				break
		for i in range(n - 1, -1, -1):
			if res[i] == 1:
				count -= 1
			else:
				break
		if count == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		if arr[i] != i + 1:
			break
	for j in range(n - 1, -1, -1):
		if arr[j] != j + 1:
			break
	if i > j:
		print(0)
		continue
	c = 1
	for k in range(i, j + 1):
		if arr[k] == k + 1:
			c = 2
			break
	print(c)


for t in range(int(input().strip())):
	n = int(input().strip())
	arr = list(map(int, input().strip().split(' ')))
	arrs = sorted(arr)
	if arr == arrs:
		print('0')
	else:
		notSamePockets = 0
		isSame = -1
		for (i, v) in enumerate(arr):
			if arrs[i] == v:
				isSame = True
			else:
				if isSame == -1:
					notSamePockets += 1
					isSame = False
				if isSame:
					isSame = False
					notSamePockets += 1
					if notSamePockets > 1:
						break
		print(notSamePockets)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	else:
		x = []
		for i in range(n):
			if a[i] - 1 != i:
				x.append(i)
		if x[-1] - x[0] + 1 == len(x):
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
		continue
	(x, y) = (0, n - 1)
	for i in range(n):
		if a[i] == i + 1:
			continue
		else:
			x = i
			break
	for i in range(n - 1, -1, -1):
		if a[i] == i + 1:
			continue
		else:
			y = i
			break
	ans = 1
	for i in range(x, y + 1):
		if a[i] == i + 1:
			ans = 2
			break
	print(ans)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	hashm = {}
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		n = inp()
		a = inlt()
		is_zero = 1
		is_one = 1
		i = 0
		while i < n:
			if a[i] != i + 1 and is_zero == 0:
				is_one = 0
				break
			elif a[i] != i + 1:
				is_zero = 0
				while i < n:
					if a[i] == i + 1:
						break
					i = i + 1
			else:
				i = i + 1
		if is_zero == 1:
			print(0)
		elif is_one == 1:
			print(1)
		else:
			print(2)
main()


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().strip().split(' ')))
	k = -1
	kki = -1
	for j in range(n):
		if a[j] != j + 1:
			kki = j
			break
	for j in range(n):
		if a[j] != j + 1:
			k = max(k, j)
	if kki == -1:
		print(0)
	else:
		kk = 0
		for j in range(kki, k):
			if a[j] == j + 1:
				kk = 1
		if kk:
			print(2)
		else:
			print(1)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	b = 0
	d = -1
	for i in range(n):
		if a[i] == i + 1:
			b += 1
		elif d == -1:
			d = i
	if b == n:
		print(0)
	else:
		e = -2
		for i in range(n - 1, -1, -1):
			if a[i] != i + 1:
				e = i
				break
		flag = 0
		for i in range(d, e + 1):
			if a[i] == i + 1:
				flag = 1
				break
		if flag == 1:
			print(2)
		else:
			print(1)

def main():
	for t in range(int(input())):
		solve()
main()


import sys
inpy = [int(x) for x in sys.stdin.read().split()]
t = inpy[0]
index = 1
for _ in range(t):
	n = inpy[index]
	nums = inpy[index + 1:index + 1 + n]
	index = index + 1 + n
	sort_nums = sorted(nums)
	start = 0
	for (i, j) in zip(nums, sort_nums):
		if i != j and start == 0:
			start = 1
		elif i == j and start == 1:
			start = 2
		elif i != j and start == 2:
			start = 3
	if start == 0:
		print(0)
	elif start == 1 or start == 2:
		print(1)
	else:
		print(2)


for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	if a == b:
		print(0)
		continue
	else:
		flag = []
		for i in range(n):
			if a[i] != i + 1:
				flag.append(i)
		if len(flag) != 0:
			if flag[-1] - flag[0] == len(flag) - 1:
				print(1)
			else:
				print(2)
		else:
			print(1)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	mistakes = 0
	b = []
	for (ind, sym) in enumerate(a):
		if ind + 1 != sym:
			mistakes += 1
			b.append('-')
		else:
			b.append('+')
	c = []
	d = []
	group = 1
	for (ind, neg) in enumerate(b):
		if ind > 0:
			if neg == b[ind - 1]:
				group += 1
			else:
				c.append(group)
				d.append(b[ind - 1])
				group = 1
	if len(a) - sum(c) != 0:
		c.append(group)
		d.append(b[-1])
	flag = 0
	for (ind, group) in enumerate(c):
		if d[ind] == '-' and group == 1:
			flag = 1
			break
	if mistakes == 0:
		print(0)
	elif (mistakes == len(a) or flag == 0) and (len(c) <= 2 and d[0] == '-' or (len(c) <= 3 and d[0] == '+')):
		print(1)
	else:
		print(2)


t = input()

def get(place):
	f = 0
	e = len(place)
	while f < e - 1 and place[f]:
		f += 1
	while e > 0 and place[e - 1]:
		e -= 1
	return place[f:e]
for opo in range(int(t)):
	n = int(input())
	a = input().split()
	a = [int(i) for i in a]
	place = [False] * n
	for i in range(n):
		if i + 1 == a[i]:
			place[i] = True
	c = 0
	if all(place):
		print(c)
	elif not any(get(place)):
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	t = 1
	ans = 0
	for i in range(n):
		if i + 1 != a[i]:
			if t > 0:
				t = 0
				ans += 1
		else:
			t = 1
	print(min(ans, 2))


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		b = a[:]
		b.sort()
		if a == b:
			print(0)
		else:
			st = -1
			en = -1
			c = 0
			for (idx, i) in enumerate(a):
				if idx + 1 != i:
					st = idx
					break
			for i in range(n - 1, -1, -1):
				if i + 1 != a[i]:
					en = i
					break
			for i in range(st, en + 1):
				if i + 1 == a[i]:
					c += 1
			if c:
				print(2)
			else:
				print(1)
	return
main()


y = int(input())
for i in range(y):
	n = int(input())
	al = input().split()
	m = list(map(int, al))
	s = []
	f = f1 = 0
	l = l1 = 0
	for j in range(n):
		if m[j] == j + 1:
			s.append(j + 1)
			if f == 0:
				f1 = j + 1
		else:
			f = 1
			l1 = j + 1
	if l1 < n:
		l1 += 1
	if m[0] != 1:
		f1 = 0
	if m[-1] != n:
		l1 = n + 1
	len1 = l1 - f1 - 1
	len2 = n - len(s)
	if len(s) == n:
		print(0)
		continue
	if len(s) == 0 or len1 == len2:
		print(1)
		continue
	print(2)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = 0
	for i in range(n):
		if d == 0:
			if a[i] != i + 1:
				d = 1
		elif d == 1:
			if a[i] == i + 1:
				d = 2
		elif d == 2:
			if a[i] != i + 1:
				d = 3
				print('2')
				break
	else:
		if d == 0:
			print('0')
		else:
			print('1')


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n = mint()
	a = list(mints())
	first = None
	for i in range(n):
		if a[i] != i + 1:
			first = i
			break
	if first is None:
		print(0)
		return
	last = None
	for i in range(first, n):
		if a[i] == i + 1:
			last = i
			break
	if last is None:
		print(1)
		return
	for i in range(last, n):
		if a[i] != i + 1:
			print(2)
			return
	print(1)
for i in range(mint()):
	solve()


t = int(input())
while t > 0:
	n = int(input())
	li = [int(i) for i in input().split()]
	(s, e) = (0, n - 1)
	while s < n - 1:
		if li[s] == s + 1:
			s += 1
		else:
			break
	while e > 0:
		if li[e] == e + 1:
			e -= 1
		else:
			break
	ans = 0
	if s < e:
		pos = False
		for i in range(s, e + 1):
			if li[i] == i + 1:
				pos = True
				break
		if pos:
			ans = 2
		else:
			ans = 1
	print(ans)
	t -= 1


def f7(seq):
	seen = set()
	seen_add = seen.add
	return [x for x in seq if not (x in seen or seen_add(x))]
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	l = a[:]
	l.sort()
	if a == l:
		print(0)
		continue
	array = []
	shit = [2]
	for i in range(n):
		if i + 1 == a[i]:
			if shit[-1] != 1:
				shit.append(1)
			array.append(1)
		else:
			if shit[-1] != 0:
				shit.append(0)
			array.append(0)
	shit = shit[1:]
	if shit == [1, 0, 1] or shit == [1, 0] or shit == [0, 1] or (shit == [0]):
		print(1)
	else:
		print(2)


import sys
input = sys.stdin.readline
MOD = 1000000007
MOD2 = 998244353
ii = lambda : int(input().strip('\n'))
si = lambda : input().strip('\n')
dgl = lambda : list(map(int, input().strip('\n')))
f = lambda : map(int, input().strip('\n').split())
il = lambda : list(map(int, input().strip('\n').split()))
ls = lambda : list(input().strip('\n'))
lsc = lambda : list(input().strip('\n').split(' '))
lsi = lambda : [int(i) for i in ls()]
let = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(ii()):
	n = ii()
	l = il()
	l2 = sorted(l)
	ind1 = -1
	ind2 = -1
	for i in range(n):
		if l[i] != l2[i]:
			ind1 = i
			break
	for i in range(n - 1, -1, -1):
		if l[i] != l2[i]:
			ind2 = i
			break
	ans = 0
	if ind1 != -1 and ind2 != -1:
		for i in range(ind1, ind2 + 1):
			if l[i] == l2[i]:
				ans = 2
				break
		if ans == 0:
			ans = 1
	print(ans)


def read_int():
	n = int(input())
	return n

def read_ints():
	ints = [int(x) for x in input().split(' ')]
	return ints

def solve(n, a):
	valid = [0 for _ in range(n)]
	for i in range(n):
		if a[i] != i + 1:
			valid[i] = 1
	if 1 not in valid:
		return 0
	if 0 not in valid:
		return 1
	cnt = 0
	for i in range(n - 1):
		if valid[i] != valid[i + 1]:
			cnt += 1
		if cnt > 2:
			return 2
	if cnt == 2 and valid[0] == 1:
		return 2
	return 1
t = read_int()
for case in range(t):
	n = read_int()
	a = read_ints()
	sol = solve(n, a)
	print(sol)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if sorted(a) == a:
		print(0)
		continue
	else:
		cnt = 0
		for i in range(len(a)):
			if i + 1 == a[i]:
				cnt += 1
		firstwrong = n + 1
		secondwrong = 0
		for i in range(len(a)):
			if i + 1 != a[i]:
				firstwrong = min(firstwrong, i)
				secondwrong = max(secondwrong, i)
		newcnt = 0
		for i in range(firstwrong, secondwrong + 1):
			if i + 1 == a[i]:
				newcnt += 1
		if cnt == 0 or newcnt == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	list1 = list(map(int, input().split()))
	list1 = [0] + list1
	c = 0
	f = 0
	cc = 0
	for i in range(1, n + 1):
		if list1[i] != i:
			c += 1
			if cc != 0:
				f = 1
		elif c != 0:
			cc += 1
	if c == 0:
		print(0)
	elif f == 1:
		print(2)
	else:
		print(1)


def splEx(s, n):
	ans = 0
	prev_not_match = 0
	for i in range(n):
		if s[i] - 1 != i:
			prev_not_match = 1
		else:
			if prev_not_match:
				ans += 1
				prev_not_match = 0
			if ans >= 2:
				break
	if prev_not_match:
		ans += 1
	return min(ans, 2)
t = int(input())
for g in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	print(splEx(s, n))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	to_s = 0
	p = 0
	num = 1
	is_ = False
	while p < n:
		if a[p] != num and (not is_):
			to_s += 1
			is_ = True
		if is_ and a[p] == num:
			is_ = False
		num += 1
		p += 1
	print(min(to_s, 2))


from collections import Counter as C, defaultdict as D, deque as Q
from operator import itemgetter as I
from itertools import product as P
from bisect import bisect_left as BL, bisect_right as BR
from heapq import heappush as HPUSH, heappop as HPOP

def main():
	for _ in range(int(input())):
		n = int(input())
		ans = 0
		a = list(map(int, input().split()))
		for i in range(n):
			if i == 0 and a[i] != 1 or (a[i] != i + 1 and a[i - 1] == i):
				ans += 1
		if ans > 2:
			print(2)
		else:
			print(ans)
main()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	p = []
	for i in range(n):
		if l[i] == i + 1:
			p.append(i + 1)
		else:
			continue
	if len(p) == n:
		print(0)
	elif len(p) == 0:
		print(1)
	else:
		f = 0
		l = len(p)
		x = 0
		y = 0
		for i in range(l):
			if p[i] == i + 1:
				x += 1
			else:
				break
		for i in range(l - 1, -1, -1):
			if p[i] == n - (l - 1 - i):
				y += 1
			else:
				break
		if l - x - y > 0:
			print(2)
		else:
			print(1)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	n = ri()
	A = rl()
	first_wrong = -1
	first_break = -1
	skip = False
	for (i, a) in enumerate(A):
		if i + 1 == a:
			if first_wrong != -1 and first_break == -1:
				first_break = i
		elif first_wrong == -1:
			first_wrong = i
		elif first_break != -1:
			skip = True
	if first_wrong == -1:
		print(0)
	elif not skip:
		print(1)
	else:
		print(2)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


t = int(input())
for test in range(t):
	n = int(input())
	r = [int(x) for x in input().split()]
	same = False
	diff = False
	diffStart = False
	diffEnd = False
	pos = True
	for i in range(n):
		if r[i] == i + 1:
			same = True
			if diffStart == True:
				diffEnd = True
		else:
			diff = True
			diffStart = True
			if diffEnd == True:
				pos = False
	if diff == False:
		print(0)
	elif pos == True:
		print(1)
	else:
		print(2)


import sys
t = int(sys.stdin.readline())
nums = []
for i in range(t):
	n = int(sys.stdin.readline())
	arr = [int(x) for x in sys.stdin.readline().strip().split()]
	nums.append(arr)
for arr in nums:
	tmp = [i + 1 - arr[i] for i in range(len(arr))]
	if tmp.count(0) == len(tmp):
		print(0)
		continue
	pos = 0
	while pos < len(tmp) and tmp[pos] == 0:
		pos += 1
	while pos < len(tmp) and tmp[pos] != 0:
		pos += 1
	while pos < len(tmp) and tmp[pos] == 0:
		pos += 1
	if pos == len(tmp):
		print(1)
		continue
	print(2)


import sys
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(sys.stdin.readline())
	list_num = list(map(int, sys.stdin.readline().split()))
	check = -1
	isall = 0
	(s, e) = (0, n - 1)
	while s < n and list_num[s] == s + 1:
		s += 1
	while e > 0 and list_num[e] == e + 1:
		e -= 1
	if e <= s:
		print(0)
		continue
	count = 0
	for i in range(s, e + 1):
		if list_num[i] == i + 1:
			count = 1
			break
	if count:
		print(2)
	else:
		print(1)


import io, os
from collections import deque
RL = lambda : list(map(int, input().split(' ')))

def smallestDivisor(n):
	if n % 2 == 0:
		return 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			return i
		i += 2
	return n
T = int(input())
for _ in range(T):
	n = int(input())
	l = RL()
	miss = 0
	flag = 1
	for i in range(n):
		if l[i] != i + 1:
			flag = 0
		else:
			if flag == 0:
				miss += 1
			flag = 1
	if flag == 0:
		miss += 1
	if miss == 0:
		print(0)
	elif miss == 1:
		print(1)
	else:
		print(2)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	iti = [0] * (n + 1)
	for i in range(n):
		if a[i] == i + 1:
			iti[i] = 1
	iti[n] = 1
	ans = 0
	for i in range(n):
		if iti[i] == 0 and iti[i + 1] == 1:
			ans += 1
	print(min(ans, 2))


from sys import stdin
t = int(stdin.readline().strip())
for i in range(t):
	n = int(stdin.readline().strip())
	A = list(map(int, stdin.readline().strip().split(' ')))
	for (i, a) in enumerate(A):
		if i + 1 != a:
			A[i] = False
		else:
			A[i] = True
	if all(A):
		print(0)
	elif not any(A):
		print(1)
	else:
		begin = 0
		while A[begin]:
			begin += 1
		end = n - 1
		while A[end]:
			end -= 1
		if not any(A[begin:end + 1]):
			print(1)
		else:
			print(2)


from time import sleep
from random import shuffle, randint
input = __import__('sys').stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	mnind = n
	mxind = -1
	for i in range(n):
		if s[i] != i + 1:
			if mnind == n:
				mnind = i
			mxind = i
	if mxind == -1:
		print(0)
	else:
		cnt = 0
		for i in range(mnind, mxind + 1):
			if s[i] == i + 1:
				cnt = 1
				break
		if cnt:
			print(2)
		else:
			print(1)


from sys import stdin

def inp():
	return stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	notOrd = 0
	last = True
	begin = 0
	end = 0
	for i in range(n):
		if last and a[i] == i + 1:
			last = True
			begin += 1
		if a[i] != i + 1:
			last = False
			notOrd += 1
	if begin == n:
		print(0)
		continue
	elif notOrd > 0 and a[n - 1] == n:
		for i in range(n):
			if a[n - 1 - i] == n - i:
				end += 1
			else:
				break
	mid = n - end - begin
	if notOrd == mid:
		print(1)
	else:
		print(2)


a = int(input())
for i in range(0, a):
	b = int(input())
	arr = list(map(int, input().split()))
	count = 0
	group = []
	pivot = 0
	for i in range(1, len(arr) + 1):
		if arr[i - 1] == i:
			count = count + 1
			if pivot == 1:
				group.append(pivot)
			pivot = 0
		else:
			pivot = 1
		if i == len(arr):
			if pivot == 1:
				group.append(pivot)
	if count == len(arr):
		print(0)
	elif count == 0 or len(group) == 1:
		print(1)
	else:
		print(2)


from collections import Counter
from collections import defaultdict
from collections import deque
import math
import heapq
import sys
import io, os
input = sys.stdin.readline
from bisect import *
rs = lambda : input().strip()
ri = lambda : int(input())
rl = lambda : list(map(int, input().strip().split()))
rls = lambda : list(map(str, input().split()))

def factors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(int(n / i))
	return l
t = int(input())
for _ in range(0, t):
	n = int(input())
	a = rl()
	a = [0] + a + [n + 1]
	x1 = 0
	x2 = 0
	for i in range(0, n + 1):
		if i == a[i] and a[i + 1] != i + 1:
			x1 = x1 + 1
		if a[i] != i and a[i + 1] == i + 1:
			x2 = x2 + 1
	if sorted(a) == a:
		print(0)
	elif x1 == 1 and x2 == 1:
		print(1)
	else:
		print(2)


import math

def answer(n, A):
	countf = -1
	counts = n
	index = 0
	for i in range(n):
		if A[i] == i + 1:
			countf = i
		else:
			break
	for i in range(n - 1, -1, -1):
		if A[i] == i + 1:
			counts = i
		else:
			break
	count = 0
	for i in range(countf + 1, counts):
		if A[i] == i + 1:
			count += 1
	if n == 1 or (countf == n - 1 and counts == 0):
		return 0
	else:
		if count == 0:
			return 1
		return 2
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(answer(n, arr))


for _ in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	if li == sorted(li):
		print(0)
		continue
	else:
		x = sorted(li)
		xs = list(range(1, n + 1))
		li = li[::-1]
		x = x[::-1]
		xs = xs[::-1]
		while li[-1] == x[-1]:
			li.pop()
			x.pop()
			xs.pop()
		li = li[::-1]
		x = x[::-1]
		xs = xs[::-1]
		while li[-1] == x[-1]:
			li.pop()
			x.pop()
			xs.pop()
		fnd = 0
		for i in range(len(li)):
			if li[i] == xs[i]:
				fnd = 1
				break
		if fnd:
			print(2)
			continue
		else:
			print(1)
			continue


for u in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	f = 0
	for i in range(n):
		if l[i] - 1 != i:
			f = 1
		elif f == 1:
			c += 1
			f = 0
		if c >= 2:
			break
	if f == 1:
		c = c + 1
	print(min(c, 2))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(f, l, d) = (-1, -1, False)
	for i in range(n):
		if a[i] != i + 1:
			f = i
			break
	if f != -1:
		for i in range(n - 1, f, -1):
			if a[i] != i + 1 and l == -1:
				l = i
			if a[i] == i + 1 and l != -1:
				d = True
				break
	if f == -1:
		print(0)
	elif l == -1:
		print(1)
	elif d == False:
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	l = 0
	r = n - 1
	for j in range(n):
		if arr[j] != j + 1:
			break
		else:
			l = j
	for j in range(1, n + 1):
		if arr[-j] != n - j + 1:
			break
		else:
			r = n - j
	if l == n - 1 or r == 0:
		print(0)
	else:
		s = 0
		for j in range(l + 1, r):
			if arr[j] == j + 1:
				s += 1
		if r - l - 1 == 2:
			print(1)
		elif s == 0:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(num) for num in input().split()]
	cnt = 0
	if a[0] == 1:
		prev = True
	else:
		cnt = 1
		prev = False
	for i in range(1, n):
		if a[i] == i + 1:
			prev = True
		else:
			if prev:
				cnt += 1
			prev = False
	print(min(cnt, 2))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	flag = 0
	for i in range(n):
		if A[i] != i + 1:
			if flag == 0:
				flag = 1
			elif flag == 2:
				flag = 3
		elif flag == 1:
			flag = 2
	if flag == 0:
		print(0)
	elif flag == 1 or flag == 2:
		print(1)
	else:
		print(2)


t = int(input())
while t:
	t = t - 1
	n = int(input())
	a = list(map(int, input().split(' ')))
	ans = 0
	a = [0] + a
	i = 1
	while i <= n:
		if i == a[i]:
			i = i + 1
			continue
		j = i + 1
		while j <= n and j != a[j]:
			j += 1
		i = j
		ans += 1
	print(min(ans, 2))


def baseball(a, n):
	if sorted(a) == a:
		print(0)
		return
	for i in range(n):
		if a[i] != i + 1:
			break
	for j in range(n - 1, -1, -1):
		if a[j] != j + 1:
			break
	for k in range(i, j + 1):
		if a[k] == k + 1:
			print(2)
			return
	else:
		print(1)
		return
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	baseball(a, n)


t = int(input())
cases = []

def func(a):
	corrects = []
	all0 = True
	all1 = True
	for i in range(len(a)):
		if i + 1 == a[i]:
			corrects.append(1)
			all0 = False
		else:
			corrects.append(0)
			all1 = False
	if all1 == True:
		return 0
	elif all0 == True:
		return 1
	corrects.append(1)
	trail_of_1 = True
	trail_counts = 1
	for i in range(len(corrects)):
		if corrects[i] == 1 and trail_of_1 == False:
			trail_counts += 1
			trail_of_1 = True
		elif corrects[i] == 0 and trail_of_1 == True:
			trail_of_1 = False
	if trail_counts <= 2:
		return 1
	else:
		return 2
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	cases.append(a)
for a in cases:
	ans = func(a)
	print(ans)


from math import sqrt
from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	n = int(input())
	l = list(map(int, input().split()))
	i = 0
	while i < n:
		if l[i] == i + 1:
			i += 1
		else:
			break
	j = n - 1
	while j >= 0:
		if l[j] == j + 1:
			j -= 1
		else:
			break
	lol = 0
	if j < i:
		print(0)
	else:
		for ii in range(i, j + 1):
			if l[ii] == ii + 1:
				lol = 1
				break
		if lol:
			print(2)
		else:
			print(1)
	t -= 1


import math
t = int(input())
for i in range(t):
	n = int(input())
	data = list(map(int, input().split()))
	sdata = sorted(data)
	if data == sdata:
		print(0)
		continue
	flag = 0
	fflag = 0
	ans = 1
	for j in range(len(data)):
		if data[j] != sdata[j]:
			if flag == 0:
				flag = 1
			if fflag == 1:
				ans = 2
				break
		elif flag == 1:
			fflag = 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	list1 = list(map(int, input().strip().split()))
	correct = []
	incorrect = []
	for i in range(n):
		if list1[i] == i + 1:
			correct.append(i)
		else:
			incorrect.append(i)
	if len(incorrect) == 0:
		print(0)
		continue
	b = 1
	for i in range(1, len(incorrect)):
		if incorrect[i] != incorrect[i - 1] + 1:
			b = 0
			break
	if b:
		print(1)
	else:
		print(2)


import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	p = []
	for i in range(n):
		if l[i] != i + 1:
			c += 1
			p.append(i)
	if c == 0:
		print(0)
	else:
		f = 0
		for i in range(c - 1):
			if p[i] + 1 != p[i + 1]:
				f = 1
		if f == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	(s, e) = (-1, len(l))
	for i in range(len(l)):
		if l[i] == i + 1:
			s = i
		else:
			break
	if s == len(l) - 1:
		sol = 0
	else:
		for i in range(len(l) - 1, 0, -1):
			if l[i] == i + 1:
				e = i
			else:
				break
		sol = 1
		for i in range(s + 1, e):
			if l[i] == i + 1:
				sol = 2
				break
	print(sol)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * n
	ch = 0
	t = 0
	for i in range(n):
		if a[i] != i + 1:
			ch = 1
			t += 1
			b[i] = 1
	if t != n:
		if t == 0:
			print(0)
		else:
			c = 0
			for i in range(n - 1):
				if b[i] == 1 and b[i + 1] == 0:
					c += 1
			if b[-1] == 1:
				c += 1
			if c == 1:
				print(1)
			else:
				print(2)
	else:
		print(1)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	sortted = True
	for i in range(n):
		if a[i] != i + 1:
			sortted = False
	if sortted:
		print(0)
		continue
	else:
		unmatch = []
		for i in range(n):
			if a[i] != i + 1:
				unmatch.append(i)
		cons = True
		for (i, x) in enumerate(unmatch[:-1]):
			if unmatch[i + 1] - unmatch[i] != 1:
				cons = False
		if cons:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	fsi = -1
	for i in range(n):
		x = arr[i]
		if x != i + 1:
			break
		fsi = i
	if fsi == n - 1:
		print(0)
		continue
	lsi = n
	for i in reversed(range(n)):
		x = arr[i]
		if x != i + 1:
			break
		lsi = i
	narr = list(map(lambda o: o - (fsi + 1), arr[fsi + 1:lsi]))
	hs = False
	for (i, x) in enumerate(narr):
		if x == i + 1:
			hs = True
			break
	print(2 if hs else 1)


def solution(test):
	answer = 0
	for i in range(len(test) - 1):
		if test[i] > test[i + 1]:
			answer = 1
	if answer != 0:
		stage = 0
		for i in range(len(test)):
			if test[i] != i + 1:
				if stage == 0:
					stage = 1
				elif stage == 1:
					continue
				else:
					answer = 2
					break
			elif stage == 1:
				stage = 2
	return answer
test_case = int(input())
for i in range(test_case):
	n = int(input())
	ar = [int(x) for x in input().split()]
	print(solution(ar))


count = int(input())
for i in range(count):
	с = input()
	arr = list(map(int, input().split()))
	arrB = [item == index + 1 for (index, item) in enumerate(arr)]
	count = 0
	for j in range(len(arrB) - 1):
		if arrB[j + 1] == True and arrB[j] == False:
			count += 1
	if not arrB[-1]:
		count += 1
	if count > 1:
		print(2)
	else:
		print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	arr_to_sort = list(map(int, input().split()))
	change_from = 0
	change_to = len(arr_to_sort) - 1
	while change_from < change_to and arr_to_sort[change_from] == change_from + 1:
		change_from += 1
	while change_to > change_from and arr_to_sort[change_to] == change_to + 1:
		change_to -= 1
	someone_at_the_place = False
	for (index, val) in enumerate(arr_to_sort[change_from:change_to + 1], start=change_from):
		if index == val - 1:
			someone_at_the_place = True
			break
	if change_to == change_from:
		print(0)
	elif someone_at_the_place:
		print(2)
	else:
		print(1)


t = int(input())
while t > 0:
	n = int(input())
	arr = list(map(int, input().rstrip().split()))
	vec = [0] * n
	sn = n
	val = 0
	for i in range(n):
		if arr[i] == i + 1:
			vec[i] += 1
			val += 1
	(left, right) = (0, 0)
	while left < n and vec[left] == 1:
		left += 1
	while right < n and vec[n - 1 - right] == 1 and (left < n - 1 - right):
		right += 1
	sn = n - left - right
	val = val - left - right
	if val == sn:
		print('0')
	elif val == 0:
		print('1')
	else:
		print('2')
	t -= 1


a = int(input())
for i in range(a):
	s = int(input())
	ans = []
	z = list(map(int, input().split()))
	mini = 0
	l = 0
	flag = 0
	i = 0
	total = 0
	while i < len(z):
		if flag == 0 and z[i] == i + 1:
			i += 1
			continue
		if flag == 0 and z[i] != i + 1:
			save = i
			size = 0
			gla = 0
			while i < len(z):
				if z[i] == i + 1:
					gla = 1
				size = max(size, z[i] - save)
				if i - save + 1 == size:
					i += 1
					break
				i += 1
			if gla:
				ans.append(2)
			else:
				ans.append(1)
	if len(ans) == 0:
		print(0)
	elif len(ans) == 1 and ans[0] == 1:
		print(1)
	else:
		print(2)


import bisect
import sys
import math
input = sys.stdin.readline
import functools
from collections import defaultdict

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def solve(case):
	n = inp()
	aa = inlt()
	if all((v == i + 1 for (i, v) in enumerate(aa))):
		return 0
	ll = [False] * n
	rr = [False] * n
	for i in range(n):
		if aa[i] != i + 1 or (i > 1 and ll[i - 1] == True):
			ll[i] = True
	for i in range(n - 1, -1, -1):
		if aa[i] != i + 1 or (i < n - 2 and rr[i + 1] == True):
			rr[i] = True
	if any((aa[i] == i + 1 and rr[i + 1] and ll[i - 1] for i in range(1, n - 1))):
		return 2
	return 1
if len(sys.argv) > 1 and sys.argv[1].startswith('input'):
	f = open('./' + sys.argv[1], 'r')
	input = f.readline
T = inp()
for i in range(T):
	res = solve(i + 1)
	print(str(res))


def func(A):
	if A == sorted(A):
		return 0
	i = 0
	while i < len(A):
		if A[i] == i + 1:
			i += 1
		else:
			break
	j = len(A) - 1
	while j >= 0:
		if A[j] == j + 1:
			j -= 1
		else:
			break
	for k in range(i, j + 1):
		if A[k] == k + 1:
			return 2
	return 1
t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	print(func(A))


from sys import stdin, stdout
import heapq as hq
from collections import defaultdict
t = int(input())
for tc in range(t):
	n = int(stdin.readline())
	ar = list(map(int, stdin.readline().split()))
	misp = 0
	res = 0
	for (i, val) in enumerate(ar):
		if val != i + 1:
			if misp == 0:
				misp = 1
				res = 1
			if misp == -1:
				res = 2
		elif misp == 1:
			misp = -1
	stdout.write(str(res) + '\n')


from itertools import groupby
t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	pos = [A[i] == i + 1 for i in range(n)]
	cnt = [i for (i, group) in groupby(pos)]
	c = cnt.count(False)
	if c == 0:
		print(0)
	elif c == 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	sorted_arr = sorted(arr)
	result = 0
	flag = arr[0] == sorted_arr[0]
	if not flag:
		result += 1
	for (arr_elem, sorted_elem) in zip(arr, sorted_arr):
		if flag:
			if arr_elem != sorted_elem:
				result += 1
				flag = False
				if result == 2:
					break
		elif arr_elem == sorted_elem:
			flag = True
	print(result)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	lis.insert(0, 0)
	if lis == sorted(lis):
		print(0)
	else:
		for i in range(1, n + 1):
			if i != lis[i]:
				break
		for j in range(n, 0, -1):
			if j != lis[j]:
				break
		for k in range(i, j + 1):
			if lis[k] == k:
				print(2)
				break
		else:
			print(1)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	is1Needed = False
	is2NeededA = False
	is2NeededB = False
	for i in range(n):
		if a[i] != i + 1:
			is1Needed = True
			break
	if not is1Needed:
		print(0)
		continue
	else:
		stage1 = False
		stage2 = False
		stage3 = False
		for i in range(n):
			if a[i] != i + 1:
				stage1 = True
			if stage1 and a[i] == i + 1:
				stage2 = True
			if stage2 and a[i] != i + 1:
				stage3 = True
				break
		if stage3:
			print(2)
		else:
			print(1)


def solve(lst, n):
	l = [True for _ in range(n)]
	for i in range(n):
		if lst[i] != i + 1:
			l[i] = False
	for j in range(n):
		if l[j] == False:
			break
	for k in range(n - 1, 0, -1):
		if l[k] == False:
			break
	res = l[j:k + 1]
	if False not in l:
		return 0
	if True in res:
		return 2
	return 1
test = int(input())
for _ in range(test):
	n = int(input())
	lst = list(map(lambda elem: int(elem), input().split(' ')))
	print(solve(lst, n))


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	N = int(input())
	A = list(map(int, input().split()))
	Query.append((N, A))
for (N, A) in Query:
	ind1 = 0
	while ind1 < N and A[ind1] == ind1 + 1:
		ind1 += 1
	ind2 = N - 1
	while ind2 >= 0 and A[ind2] == ind2 + 1:
		ind2 -= 1
	if ind1 == N:
		ans = 0
	else:
		p = False
		for i in range(ind1, ind2 + 1):
			if A[i] == i + 1:
				p = True
		if p:
			ans = 2
		else:
			ans = 1
	print(ans)


t = int(input())
while t > 0:
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	else:
		cnt = 0
		new = True
		for i in range(n):
			if a[i] == i + 1:
				new = True
			else:
				if new:
					cnt += 1
				new = False
		if cnt == 1:
			print(1)
		else:
			print(2)
	t -= 1


t = int(input())
for _ in range(t):
	lenAr = int(input())
	ar = list(map(int, input().split()))
	(var1, var2, var3) = (0, 0, 0)
	for idx in range(lenAr):
		if ar[idx] != idx + 1:
			var1 = idx + 1
			break
	if not var1:
		print(0)
	else:
		for idx in range(lenAr - 1, -1, -1):
			if ar[idx] != idx + 1:
				var2 = idx + 1
				break
		for idx in range(var1 - 1, var2):
			if ar[idx] == idx + 1:
				var3 = idx + 1
				break
		if not var3:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l = [0] + l
	c = 0
	i = 1
	while i <= n:
		temp = 0
		while i <= n and i != l[i]:
			temp = 1
			i += 1
		if temp == 1:
			temp = 0
			c += 1
		i += 1
	if c > 1:
		print(2)
	else:
		print(c)


for test in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = sorted(a)
	t = [a[i] == s[i] for i in range(n)]
	counter = 0
	i = 0
	while i < n:
		if not t[i]:
			counter += 1
			while i < n and (not t[i]):
				i += 1
		i += 1
	if counter > 1:
		print(2)
	else:
		print(counter)


from sys import stdin, stdout

def omkar_and_baseball(n, a):
	ast = sorted(a)
	l = 0
	r = n - 1
	while l < n and a[l] == ast[l]:
		l += 1
	while r >= 0 and a[r] == ast[r]:
		r -= 1
	if l >= r:
		return 0
	for i in range(l, r + 1):
		if a[i] == ast[i]:
			return 2
	return 1
t = int(stdin.readline())
for i in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	ans = omkar_and_baseball(n, a)
	print(ans)


from math import *

def r1(t):
	return t(input())

def r2(t):
	return [t(i) for i in input().split()]
for _ in range(r1(int)):
	n = r1(int)
	a = r2(int)
	g = True
	for i in range(n):
		if a[i] != i + 1:
			g = False
			break
	if g:
		print(0)
		continue
	g = True
	c = 0
	p = False
	for i in range(n):
		if a[i] != i + 1:
			if p == False:
				c += 1
				p = True
		else:
			p = False
	print(min(c, 2))


import sys
from math import ceil, sqrt, sin, pi, tan
from collections import defaultdict
read = sys.stdin.buffer.readline
import heapq
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())

def ispd(s):
	n = len(s)
	if s[:n // 2] == s[[n // 2 + 1, n // 2][n % 2 == 0]:][::-1]:
		return True
	return False
for _ in range(cin()):
	n = cin()
	a = li()
	noe = 0
	flag = False
	ans = 1
	for i in range(n):
		if i + 1 != a[i]:
			noe += 1
			if flag:
				ans = 2
				break
		elif noe > 0:
			flag = True
	if noe == 0:
		print(noe)
	else:
		print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(lambda x: int(x) - 1, input().split()))
	for i in range(n):
		if l[i] != i:
			break
	else:
		print(0)
		continue
	for j in range(i, n):
		if l[j] == j:
			break
	else:
		print(1)
		continue
	for k in range(j, n):
		if l[k] != k:
			break
	else:
		print(1)
		continue
	print(2)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 1
	i = 0
	for i in range(n):
		if a[i] != i + 1:
			break
	if i == n - 1 and a[i] == n:
		print(0)
		continue
	j = n - 1
	for j in range(n - 1, -1, -1):
		if a[j] != j + 1:
			break
	for k in range(i, j + 1):
		if a[k] == k + 1:
			ans = 2
			break
	print(ans)


def problem1():
	n = int(input())
	j = 1
	a = [1] * n
	print(*a)
from math import sqrt
primes = []

def problem2():
	n = int(input())
	if n % 2 == 0:
		print(n // 2, n // 2)
		return
	i = 0
	m = sqrt(n)
	while n % primes[i] != 0:
		i += 1
		if primes[i] > m:
			print(1, n - 1)
			return
	j = n // primes[i]
	print(j, n - j)

def problem3():
	n = int(input())
	l = list(map(int, input().split()))
	z = True
	for i in range(n):
		if l[i] != i + 1:
			z = False
	if z:
		print(0)
		return
	i = 0
	while l[i] == i + 1:
		i += 1
	while i < n and l[i] != i + 1:
		i += 1
	if i == n:
		print(1)
		return
	for j in range(i, n):
		if l[j] != j + 1:
			print(2)
			return
	print(1)
	return
cases = int(input())
for _ in range(cases):
	problem3()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * n
	flag = False
	for i in range(1, n + 1):
		if a[i - 1] == i:
			b[i - 1] = 1
	for i in b:
		if i == 0:
			flag = True
			break
	if flag:
		j = n - 1
		while j >= 0 and b[j] == 1:
			j -= 1
		i = 0
		while i < n and b[i] == 1:
			i += 1
		for k in range(i, j + 1):
			if b[k] == 1:
				print(2)
				break
		else:
			print(1)
	else:
		print(0)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = array()
	if a == sorted(a):
		print(0)
		continue
	ans = 1
	start = 0
	while a[start] == start + 1:
		start += 1
	end = n - 1
	while a[end] == end + 1:
		end -= 1
	for i in range(start, end + 1):
		if a[i] == i + 1:
			ans = 2
			break
	print(ans)


for lo in range(int(input())):
	n = int(input())
	ls = [int(x) for x in input().split()]
	c1 = 0
	c2 = 0
	for i in range(n):
		if ls[i] != i + 1:
			c1 = 1
		if ls[i] == i + 1:
			c2 = 1
	if c1 == 1 and c2 == 0:
		print(1)
		continue
	if c1 == 0 and c2 == 1:
		print(0)
		continue
	c1 = c2 = 0
	for i in range(n):
		if ls[i] == i + 1 and c1 == 1:
			c2 = 1
		if ls[i] != i + 1 and c2 == 1:
			c1 = 2
			break
		if ls[i] != i + 1 and c2 == 0:
			c1 = 1
	print(c1)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
		continue
	b = []
	for i in range(n):
		if a[i] == i + 1:
			b.append(1)
		else:
			b.append(0)
	c = [b[0]]
	for i in range(1, n):
		if c[-1] != b[i]:
			c.append(b[i])
	if c.count(0) == 1:
		print(1)
	else:
		print(2)


import math
t = int(input())
Maxn = 210000
while t > 0:
	t -= 1
	n = int(input())
	a = input().split()
	flag = 0
	for i in range(0, n):
		if int(a[i]) != i + 1:
			flag = 1
			break
	if flag == 0:
		print('0')
		continue
	flag = 0
	for i in range(0, n):
		if int(a[i]) == i + 1:
			a[i] = 1
		else:
			a[i] = 0
	if a[0] == 0:
		flag = 1
	for i in range(1, n):
		if a[i] == 0 and a[i - 1] == 1:
			flag += 1
	if flag > 1:
		print('2')
	else:
		print('1')


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for xyz in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	pos = [-1] * (n + 1)
	for i in range(0, n):
		pos[l[i]] = i + 1
	corrpos = [0]
	for i in range(1, n + 1):
		if pos[i] == i:
			corrpos.append(i)
	corrpos.append(n + 1)
	c = 0
	for i in range(1, len(corrpos)):
		if corrpos[i] - corrpos[i - 1] != 1:
			c += 1
	print(min(c, 2))


for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	main = []
	for i in range(n):
		if lst[i] != i + 1:
			main.append(i + 1)
	if len(main) == 0:
		print(0)
	elif len(main) == max(main) - min(main) + 1:
		print(1)
	else:
		print(2)


for i in range(int(input())):
	n = int(input())
	l = [int(num) for num in input().split()]
	p = [j for j in range(n) if l[j] != j + 1]
	if len(p) == 0:
		print('0')
	elif len(p) == p[len(p) - 1] - p[0] + 1:
		print('1')
	else:
		print('2')


for _ in range(int(input())):
	n = int(input())
	p = [*map(int, input().split())]
	if p == sorted(p):
		print(0)
		continue
	(cnt, l, r) = (0, 0, 0)
	for i in range(n):
		if i + 1 != p[i]:
			l = i
			break
	for i in range(n):
		if i + 1 != p[i]:
			r = i
	for i in range(l, r + 1):
		if i + 1 == p[i]:
			cnt += 1
	if cnt == 0:
		print(1)
	else:
		print(2)


from __future__ import division, print_function
from sys import stdin, stdout
import bisect
import math
import heapq
i_m = 9223372036854775807

def inin():
	return int(input())

def stin():
	return input()

def spin():
	return map(int, stin().split())

def lin():
	return list(map(int, stin().split()))

def matrix(n):
	return [list(map(int, input().split())) for i in range(n)]

def count2Dmatrix(i, list):
	return sum((c.count(i) for c in list))

def modinv(n, p):
	return pow(n, p - 2, p)

def GCD(x, y):
	x = abs(x)
	y = abs(y)
	if min(x, y) == 0:
		return max(x, y)
	while y:
		(x, y) = (y, x % y)
	return x

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l
prime = []

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f
q = []

def dfs(n, d, v, c):
	global q
	v[n] = 1
	x = d[n]
	q.append(n)
	j = c
	for i in x:
		if i not in v:
			f = dfs(i, d, v, c + 1)
			j = max(j, f)
	return j
for _ in range(inin()):
	n = inin()
	a = lin()
	l = []
	if sorted(a) == a:
		print(0)
		continue
	for i in range(n):
		if i + 1 != a[i]:
			l.append(a[i])
	if len(l) == max(l) - min(l) + 1:
		print(1)
	else:
		print(2)


def main():
	(n,) = map(int, input().split(' '))
	a = list(map(int, input().split(' ')))
	s = [i for i in range(n) if a[i] != i + 1]
	if len(s) == 0:
		print(0)
	elif s[-1] - s[0] + 1 == len(s):
		print(1)
	else:
		print(2)
for _ in range(int(input())):
	main()


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = a[:]
	b.sort()
	(start, end) = (0, n - 1)
	cnt = 0
	for x in range(n):
		if a[x] == b[x]:
			start += 1
		else:
			break
	if start == n:
		print(0)
		continue
	for x in range(n - 1, -1, -1):
		if a[x] == b[x]:
			end -= 1
		else:
			break
	for x in range(start + 1, end):
		if a[x] == b[x]:
			cnt += 1
	if cnt == 0:
		print(1)
	else:
		print(2)


import math
t = int(input(''))
while t > 0:
	n = int(input(''))
	a = list(map(int, input().split()))
	copy = list(a)
	a.sort()
	count = 0
	start = 0
	end = n - 1
	for i in range(0, n):
		if a[i] != copy[i]:
			start = i
			break
	for j in range(-1, -n - 1, -1):
		if a[j] != copy[j]:
			end = n + j
			break
	new_a = a[start:end + 1]
	new_copy = copy[start:end + 1]
	new_length = end + 1 - start
	for checker in range(new_length):
		if new_a[checker] == new_copy[checker]:
			count += 1
	if count == new_length:
		ans = 0
	elif count == 0:
		ans = 1
	else:
		ans = 2
	print(ans)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(count, start, end) = (0, 0, 0)
	s = e = True
	for i in range(n):
		if a[i] == i + 1:
			count += 1
			if s:
				start += 1
		else:
			s = False
		if a[-(i + 1)] == n - i and e:
			end += 1
		else:
			e = False
	if count == n:
		print(0)
	else:
		count = count - start - end
		if count == 0:
			print(1)
		else:
			print(2)


t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	done = 0
	ans = 0
	for i in range(n):
		if li[i] != i + 1:
			if done == 0:
				mark = i
				done = 1
			else:
				if i != mark + 1:
					ans += 1
				mark = i
	if done == 0:
		print(0)
	elif ans == 0:
		print(1)
	else:
		print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	sorteda = sorted(a)
	if a == sorteda:
		print(0)
	else:
		works = []
		for i in range(n):
			if a[i] == i + 1:
				works.append(1)
			else:
				works.append(0)
		start = 0
		end = 0
		for i in range(n):
			if works[i]:
				start += 1
			else:
				break
		for i in range(n - 1, -1, -1):
			if works[i]:
				end += 1
			else:
				break
		if start > end:
			sub = works[start:]
		elif end > start:
			sub = works[:-end]
		else:
			sub = works[start:n - end]
		if sum(sub) == 0:
			print(1)
		else:
			print(2)


from functools import reduce

def factors(n):
	return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
		continue
	c = []
	for i in range(n):
		if a[i] != i + 1:
			c.append(i)
	d = []
	for i in range(len(c) - 1):
		d.append(c[i + 1] - c[i])
	m = max(d)
	if m == min(d) and m == 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	index = [-1] * n
	count = 0
	temp = 0
	for i in range(n):
		if ar[i] != i + 1:
			if temp == 0:
				count += 1
			temp += 1
			index[i] = ar[i] - 1
		else:
			temp = 0
	if count == 0:
		print(0)
	elif count == 1:
		print(1)
	else:
		print(2)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = sorted(l)
	s = []
	if l == l1:
		print(0)
	else:
		for i in range(n):
			if l[i] == i + 1:
				s.append(1)
			else:
				s.append(0)
		while s[-1] == 1:
			s = s[:-1]
		while s[0] == 1:
			s = s[1:]
		if 1 in s:
			print(2)
		else:
			print(1)


import os, io
from sys import stdout
import collections
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys

def primes(n):
	sieve = [True] * n
	for i in range(3, int(n ** 0.5) + 1, 2):
		if sieve[i]:
			sieve[i * i::2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
	return [2] + [i for i in range(3, n, 2) if sieve[i]]

def binomial_coefficient(n, k):
	if 0 <= k <= n:
		ntok = 1
		ktok = 1
		for t in range(1, min(k, n - k) + 1):
			ntok *= n
			ktok *= t
			n -= 1
		return ntok // ktok
	else:
		return 0

def powerOfK(k, max):
	if k == 1:
		return [1]
	if k == -1:
		return [-1, 1]
	result = []
	n = 1
	while n <= max:
		result.append(n)
		n *= k
	return result

def divisors(n):
	i = 1
	result = []
	while i * i <= n:
		if n % i == 0:
			if n / i == i:
				result.append(i)
			else:
				result.append(i)
				result.append(n / i)
		i += 1
	return result

def distance(xa, ya, xb, yb):
	return ((ya - yb) ** 2 + (xa - xb) ** 2) ** 0.5

def digitsSum(n):
	if n == 0:
		return 0
	r = 0
	while n > 0:
		r += n % 10
		n //= 10
	return r

def isValid(i, j, n, m):
	return i >= 0 and i < n and (j >= 0) and (j < m)

def print_grid(grid):
	for line in grid:
		print(' '.join(map(str, line)))

def kadane(a, size):
	max_so_far = 0
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def prefixSum(arr):
	for i in range(1, len(arr)):
		arr[i] = arr[i] + arr[i - 1]
	return arr

def ceil(n, d):
	if n % d == 0:
		return n // d
	else:
		return n // d + 1

def _abs(a, b):
	return int(abs(a - b))

def evenodd(l):
	even = [e for e in l if e & 1 == 0]
	odd = [e for e in l if e & 1]
	return (even, odd)
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	correct = []
	incorrect = []
	for (i, v) in enumerate(l):
		if i + 1 == v:
			correct.append((i, v))
		else:
			incorrect.append((i, v))
	c = len(correct)
	if c == n:
		print(0)
	elif c == 0:
		print(1)
	else:
		ic = sorted(incorrect, key=lambda x: x[0])
		done = False
		for i in range(1, len(ic)):
			if ic[i][0] != ic[i - 1][0] + 1:
				print(2)
				done = True
				break
		if not done:
			print(1)


def solve():
	n = int(input())
	arr = [int(v) for v in input().split()]
	moves = 0
	l = 0
	r = n - 1
	while r >= 0:
		if r + 1 != arr[r]:
			break
		r -= 1
	if r < 0:
		print(0)
		return
	while l < r:
		if l + 1 != arr[l]:
			break
		l += 1
	someorder = False
	ans = 1
	for i in range(l, r + 1):
		if i + 1 == arr[i]:
			someorder = True
			break
	if someorder:
		ans += 1
	print(ans)
t = int(input())
for _ in range(t):
	solve()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	i = 0
	while i < n:
		if a[i] - 1 == i:
			i += 1
		else:
			j = i
			while j < n and a[j] - 1 != j:
				j += 1
			i = j
			c += 1
	print(min(c, 2))


import sys
input = sys.stdin.readline

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0, hi=None):
	if hi == None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	a = int_array()
	if a == sorted(a):
		print(0)
	else:
		x = 0
		arr = []
		for i in range(n):
			if i + 1 != a[i]:
				arr.append(i)
		if arr[-1] - arr[0] + 1 == len(arr):
			x = 1
		if x:
			print(1)
		else:
			print(2)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	n = int(inputi())
	aa = [int(a) for a in inputi().split()]
	mc = 0
	starting = True
	ec = 0
	sc = 0
	for (i, a) in enumerate(aa, 1):
		if a == i:
			mc += 1
			ec += 1
		else:
			if starting:
				starting = False
				sc = i - 1
			ec = 0
	if mc == n:
		print(0)
	elif mc - sc - ec == 0:
		print(1)
	else:
		print(2)

def main():
	t = int(inputi())
	for _ in range(t):
		solve()
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	res = 0
	q = 0
	for i in range(n):
		if a[i] - 1 != i:
			q = 1
		elif q == 1:
			res += 1
			q = 0
		if res >= 2:
			break
	if q == 1:
		res += 1
	print(min(res, 2))


t = int(input())
for case in range(t):
	n = int(input())
	a = input().split()
	swap0 = True
	swap1 = True
	changes = 0
	prevNum = int(a[0])
	startWithT = True
	if prevNum == 1:
		startWithT = True
	else:
		startWithT = False
	for i in range(1, n):
		if i + 1 == int(a[i]):
			if prevNum != i:
				changes += 1
		elif prevNum == i:
			changes += 1
		prevNum = int(a[i])
	if changes == 0 and startWithT == True:
		print(0)
	elif changes == 0 and startWithT == False:
		print(1)
	elif changes == 1:
		print(1)
	elif changes == 2 and startWithT == True:
		print(1)
	else:
		print(2)


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	a = inlt()
	q = [a[i] - i - 1 for i in range(len(a))]
	if len(set(q)) == 1 and q[0] == 0:
		print(0)
	elif 0 not in q[1:-1] or (a[0] == 2 and a[1] == 1 and (n == 2 * a[0]) and (n <= 6)):
		print(1)
	else:
		print(2)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a, qw):
	q = [0] * qw
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = (q[ord(a[i]) - 97], 1)
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	b = [[0] * n for i in range(n)]
	for i in range(len(a)):
		for j in range(len(a)):
			b[i][j] = a[j][i]
	return b
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = 0
	for i in range(n):
		if a[i] == i + 1:
			x += 1
	if x == len(a):
		print(0)
	elif x == 0:
		print(1)
	else:
		for i in range(n):
			if a[i] != i + 1:
				s = i
				break
		for i in range(n - 1, s, -1):
			if a[i] != i + 1:
				e = i
				break
		o = 0
		for i in range(s + 1, e):
			if a[i] == i + 1:
				o = 1
				break
		if o == 1:
			print(2)
		else:
			print(1)


def cin():
	return map(int, input().split())
for t in range(int(input())):
	n = int(input())
	a = list(cin())
	cnt = 0
	for i in range(n):
		if a[i] == i + 1:
			cnt += 1
	if cnt == n:
		print(0)
	else:
		(l, r) = (0, 0)
		for i in range(n):
			if a[i] != i + 1:
				l = i
				break
		for i in range(n - 1, -1, -1):
			if a[i] != i + 1:
				r = n - i - 1
				break
		cnt = cnt - l - r
		if not cnt:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	cp = 0
	wp = 0
	rt = [i for i in range(1, n + 1)]
	for i in range(n):
		if l[i] == rt[i]:
			cp += 1
		else:
			wp += 1
	if wp == 0:
		print(0)
	elif cp == 0:
		print(1)
	else:
		i = 0
		while l[i] == rt[i]:
			i = i + 1
			cp = cp - 1
			if i == n:
				break
		i = n - 1
		while l[i] == rt[i]:
			i = i - 1
			cp = cp - 1
			if i == -1:
				break
		if cp == 0:
			print(1)
		else:
			print(2)


t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	a = input()
	A = list(map(int, list(a.split())))
	c = 0
	for i in range(n):
		if A[i] == i + 1:
			c = c + 1
	if c == 0:
		print(1)
	elif c == n:
		print(0)
	else:
		for i in range(0, n):
			if A[i] != i + 1:
				break
		for j in range(n - 1, -1, -1):
			if A[j] != j + 1:
				break
		c = 0
		for k in range(i, j + 1):
			if A[k] == k + 1:
				c = c + 1
		if c == 0:
			print(1)
		else:
			print(2)


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	ans = 0
	while i < n:
		if a[i] == i + 1:
			i += 1
			continue
		j = i
		while j < n and a[j] != j + 1:
			j += 1
		ans += 1
		i = j
	print(min(ans, 2))
t = int(input())
for _ in range(t):
	solve()


from sys import stdin, exit
input = stdin.readline

def i():
	return input()

def ii():
	return int(input())

def iis():
	return map(int, input().split())

def liis():
	return list(map(int, input().split()))

def print_array(a):
	print(' '.join(map(str, a)))

def check(a, s):
	init = 0
	for i in range(len(a)):
		if a[i] != s[i]:
			init = i
			break
	end = 0
	for i in range(len(a) - 1, -1, -1):
		if a[i] != s[i]:
			end = i
			break
	for i in range(init, end + 1):
		if a[i] == s[i]:
			print(2)
			break
	else:
		print(1)
t = ii()
for _ in range(t):
	n = ii()
	a = liis()
	s = sorted(a)
	if s == a:
		print(0)
	else:
		for i in range(len(a)):
			if a[i] == s[i]:
				check(a, s)
				break
		else:
			print(1)


import math
t = int(input())
for i in range(t):
	n = int(input())
	array = [int(s) for s in input().split()]
	matching = []
	for i in range(n):
		if i + 1 == array[i]:
			matching.append(1)
		else:
			matching.append(0)
	if sum(matching) == n:
		print(0)
		continue
	left = 0
	right = n
	while right - left > 1:
		mid = (right + left) // 2
		if sum(matching[:mid]) == mid:
			left = mid
		else:
			right = mid
	ans_1 = left
	left = 0
	right = n
	while right - left > 1:
		mid = (right + left) // 2
		if sum(matching[mid:]) == n - mid:
			right = mid
		else:
			left = mid
	ans_2 = right
	if sum(matching[ans_1 + 1:ans_2]) == 0:
		print(1)
		continue
	elif n - ans_2 == sum(matching) or ans_1 == sum(matching):
		print(1)
		continue
	else:
		print(2)


t = int(input())
while t > 0:
	n = int(input())
	a = [int(i) for i in input().split()]
	flag = False
	temp = False
	count = 0
	for i in range(n):
		if a[i] != i + 1 and temp == True:
			flag = True
			break
		elif a[i] != i + 1:
			count += 1
		elif a[i] == i + 1 and count > 0:
			temp = True
	if flag:
		print(2)
	elif count > 0:
		print(1)
	else:
		print(0)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(start, ans, c) = (0, 0, 0)
	end = n
	for i in range(n - 1, -1, -1):
		if a[i] != i + 1:
			end = i + 1
			break
		else:
			end = i
	for i in range(n):
		if a[i] != i + 1:
			start = i
			break
		else:
			start = i
	if start < end:
		for i in range(start, end):
			if a[i] == i + 1:
				c = 1
				break
		if c == 1:
			print(2)
		else:
			print(1)
	else:
		print(0)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = [int(i) for i in input().split()]
	diff = []
	for i in range(n):
		diff.append(i + 1 - a[i])
	l = 0
	while l < n:
		if not diff[l]:
			l += 1
		else:
			break
	r = n - 1
	while r > l:
		if not diff[r]:
			r -= 1
		else:
			break
	z_count = 0
	for i in range(l, r + 1):
		if not diff[i]:
			z_count += 1
	if l < r:
		if z_count:
			print(2)
		else:
			print(1)
	else:
		print(0)


for _ in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	(ans, n) = (0, 0)
	for i in range(a):
		if b[i] - 1 != i:
			n = 1
		else:
			if n == 1:
				ans += 1
			n = 0
		if ans >= 2:
			break
	if n == 1:
		ans += 1
	print(min(ans, 2))


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	c = 0
	for j in range(0, n):
		if j > 0 and arr[j - 1] == j and (arr[j] != j + 1) and (c == 1):
			c = 2
		if arr[j] != j + 1 and c == 0:
			c = 1
	print(c)


def solve(t):
	if not t:
		return
	n = int(input())
	a = list(input().split())
	for i in range(0, n):
		a[i] = int(a[i])
	k = 0
	for i in range(0, n):
		if i + 1 != a[i]:
			k += 1
	if not k:
		print(0)
	else:
		res = 1
		cnt = 0
		for i in range(0, n):
			if i + 1 == a[i]:
				if cnt == 1:
					cnt += 1
			elif not cnt:
				cnt += 1
			elif cnt == 2:
				res = 2
				break
		print(res)
	solve(t - 1)
tests = int(input())
solve(tests)


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(v) for v in input().split()]
	f = 0
	fl = 0
	j = 0
	an = 0
	while j < n:
		if a[j] == j + 1:
			j = j + 1
		else:
			break
	if j == n:
		an = 0
	else:
		while j < n:
			if a[j] != j + 1:
				an = 1
				j = j + 1
			else:
				break
		while j < n:
			if a[j] == j + 1:
				j = j + 1
			else:
				an = 2
				break
	print(an)


import sys
import math
import bisect
from sys import stdin
from itertools import groupby
from heapq import heapify, heappop, heappush
from collections import deque, Counter, OrderedDict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__

def neo():
	return map(int, input().split())

def Neo():
	return list(map(int, input().split()))
for _ in range(int(input())):
	N = int(input())
	A = Neo()
	i = 0
	j = N - 1
	while i < N:
		if A[i] != i + 1:
			break
		i += 1
	if i == N:
		print(0)
		continue
	while j >= 0:
		if A[j] != j + 1:
			break
		j -= 1
	A = A[i:j + 1]
	t = 0
	for k in A:
		if k == i + 1:
			t += 1
		i += 1
	print(2) if t > 0 else print(1)


t = int(input())
for case in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if a == list(range(1, n + 1)):
		ans = 0
	else:
		wrong = 0
		consecutive_wrong = 0
		most_wrong = 0
		for i in range(1, n + 1):
			wrong += int(a[i - 1] != i)
			consecutive_wrong += int(a[i - 1] != i)
			most_wrong = max(most_wrong, consecutive_wrong)
			if a[i - 1] == i:
				consecutive_wrong = 0
		if wrong == n or most_wrong == wrong:
			ans = 1
		else:
			ans = 2
	print(ans)


for _ in range(0, int(input())):
	(n, a) = (int(input()), list(map(int, input().split())))
	(i, j, c, cr) = (0, len(a) - 1, 1, n)
	while i < len(a) and a[i] == i + 1:
		i += 1
	while j >= 0 and a[j] == j + 1:
		j -= 1
	if i >= j:
		print(0)
	else:
		f = 0
		for k in range(i, j + 1):
			if a[k] == k + 1:
				f = 1
				break
		if f == 0:
			print(1)
		else:
			print(2)


t = int(input())
for s in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = [i for i in range(1, n + 1)]
	c = []
	add = 0
	for i in range(n):
		if a[i] != b[i]:
			c.append(b[i])
			add += 1
	if add == 0:
		print(0)
	elif add == n:
		print(1)
	else:
		flag = 0
		for i in range(add - 1):
			if c[i] + 1 != c[i + 1]:
				flag = -1
				break
		if flag == -1:
			print(2)
		else:
			print(1)


def sorted_ends(array):
	front_idx = 0
	while front_idx < len(array) and array[front_idx] == front_idx + 1:
		front_idx += 1
	back_idx = len(array) - 1
	while back_idx >= 0 and array[back_idx] == back_idx + 1:
		back_idx -= 1
	for i in range(front_idx, back_idx + 1):
		if array[i] == i + 1:
			return False
	return True

def solve(array):
	if array == sorted(array):
		return 0
	if sorted_ends(array):
		return 1
	else:
		return 2
cases = int(input())
for k in range(cases):
	length = int(input())
	array = [int(i) for i in input().split(' ')]
	print(solve(array))


t = int(input())
for i in range(t):
	n = int(input())
	ar = [int(i) for i in input().split()]
	count = 0
	bo = True
	fo = True
	count = 0
	mount = 0
	fount = 0
	for x in range(n):
		if ar[x] != x + 1:
			count += 1
		else:
			pass
		if ar[x] == x + 1 and bo == True:
			fount += 1
		else:
			bo = False
		if ar[-(x + 1)] == n - x and fo == True:
			mount += 1
		else:
			fo = False
	if count == 0:
		print(0)
	elif count == n - (fount + mount):
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	started = False
	ended = False
	two = False
	L = map(int, input().split())
	for (j, x) in enumerate(L):
		if x == j + 1 and started:
			ended = True
		if x != j + 1 and (not started):
			started = True
		if x != j + 1 and ended:
			print(2)
			two = True
			break
	if not started:
		print(0)
	if started and (not two):
		print(1)


for i in range(int(input())):
	N = int(input())
	counter = 0
	lineup = [int(x) for x in input().split()]
	for i in range(N):
		if lineup[i] == i + 1:
			counter += 1
	if counter == N:
		print('0')
		continue
	check1 = 0
	while lineup[check1] == check1 + 1:
		check1 += 1
		counter -= 1
	check1 = 0
	while lineup[N - 1 - check1] == N - check1:
		check1 += 1
		counter -= 1
	if counter == 0:
		print('1')
	else:
		print('2')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * n
	c = 1
	ans = 0
	for i in range(n):
		if not a[i] == i + 1:
			if c == 1:
				ans += 1
				c = 0
		else:
			c = 1
	ans = min(ans, 2)
	print(ans)


cases = int(input())
for i in range(cases):
	l1 = int(input())
	l2 = input().split(' ')
	arr = []
	for a in l2:
		arr.append(int(a))
	copy = arr[:]
	copy.sort()
	if copy == arr:
		print(0)
	else:
		arr2 = []
		for (b, c) in zip(arr, copy):
			if b != c:
				arr2.append(0)
			else:
				arr2.append(1)
		for d in range(len(arr2)):
			ele = arr2[d]
			if ele == 0:
				left = d
				break
		for e in range(-1, -(len(arr2) + 1), -1):
			ele2 = arr2[e]
			if ele2 == 0:
				right = len(arr2) + e
				break
		temp = arr2[left:right + 1]
		if temp.count(1) > 0:
			print(2)
		else:
			print(1)


def solve(n, arr):
	(intervals, org, dup, lo) = ([], 0, 0, 0)
	(last, prev_last) = (-1, -1)
	for i in range(len(arr)):
		if arr[i] != i + 1:
			prev_last = last
			last = 1
			dup += 1
		else:
			prev_last = last
			last = 2
			org += 1
		if last != prev_last and last == 1:
			lo += 1
	if org == n:
		print('0')
	elif dup == n:
		print('1')
	elif lo >= 2:
		print('2')
	else:
		print('1')
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	solve(n, arr)


import sys
import random
from fractions import Fraction
from math import *

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def finput():
	return float(input())

def tinput():
	return input().split()

def linput():
	return list(input())

def rinput():
	return map(int, tinput())

def fiinput():
	return map(float, tinput())

def rlinput():
	return list(map(int, input().split()))

def trinput():
	return tuple(rinput())

def srlinput():
	return sorted(list(map(int, input().split())))

def NOYES(fl):
	if fl:
		print('NO')
	else:
		print('YES')

def YESNO(fl):
	if fl:
		print('YES')
	else:
		print('NO')

def main():
	n = iinput()
	q = rlinput()
	w = q.copy()
	if q == sorted(w):
		print(0)
	else:
		res = 1
		for i in range(n):
			if i + 1 == q[i]:
				res = 2
		if res == 1:
			print(1)
		else:
			(l, r) = (0, n - 1)
			for i in range(n):
				if i + 1 != q[i]:
					l = i
					break
			for i in range(n - 1, l, -1):
				if i + 1 != q[i]:
					r = i
					break
			q = q[l:r + 1]
			n = len(q)
			m = min(q)
			for i in range(n):
				if m + i == q[i]:
					print(2)
					return 0
			print(1)
for i in range(iinput()):
	main()


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(j) for j in input().split()]
	l = []
	for i in range(n):
		if i + 1 != a[i]:
			l.append(i)
	flag = True
	for i in range(len(l) - 1):
		if l[i + 1] - l[i] != 1:
			flag = False
	if len(l) == 0:
		print(0)
	elif not flag:
		print(2)
	else:
		print(1)


t = int(input())
for tt in range(t):
	n = int(input())
	a = [int(i) for i in input().split(' ', n - 1)]
	g = 0
	k = 0
	for i in range(n):
		if a[i] == i + 1 and g == 0:
			g = 1
		elif a[i] != i + 1 and g == 0:
			g = 2
			k = 1
		elif a[i] != i + 1 and g == 1:
			g = 3
			k = 1
		elif a[i] == i + 1 and g == 3:
			g = 6
			k = 1
		elif a[i] == i + 1 and g == 2:
			g = 4
			k = 1
		elif a[i] != i + 1 and g == 4:
			k = 2
			break
		elif a[i] != i + 1 and g == 6:
			k = 2
			break
	print(k)


import sys
input = sys.stdin.readline
scan_int = lambda : int(input())
scan_string = lambda : input().rstrip()
read_list = lambda : list(read())
read = lambda : map(int, input().split())
read_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(beauty, s, n, count):
	pass
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	n = scan_int()
	a = read_list()
	if a == sorted(a):
		print(0)
		return
	l = 0
	for i in range(n):
		if a[i] == i + 1:
			l = i + 1
		else:
			break
	r = n
	for i in range(n - 1, 0, -1):
		if a[i] == i + 1:
			r = i
		else:
			break
	for i in range(l, r):
		if a[i] == i + 1:
			print(2)
			return
	print(1)
for _ in range(int(input())):
	solve()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = -1
	r = n + 1
	for i in range(n):
		if a[i] != i + 1:
			l = i
			break
	for i in range(n - 1, -1, -1):
		if a[i] != i + 1:
			r = i
			break
	if l == -1:
		print(0)
	else:
		c = 0
		for j in range(l, r + 1):
			if a[j] == j + 1:
				c += 1
		if c == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	res = []
	for i in range(n):
		if i + 1 == arr[i]:
			res.append(0)
		else:
			res.append(1)
	s = -1
	e = -1
	for i in range(n):
		if res[i] == 1:
			s = i
			break
	for i in range(n - 1, -1, -1):
		if res[i] == 1:
			e = i
			break
	if s == -1 and e == -1:
		print(0)
	else:
		lock = 0
		for i in range(s, e + 1):
			if res[i] == 0:
				lock = 1
				break
		if lock == 1:
			print(2)
		else:
			print(1)


def testcase():
	n = int(input())
	arr = list(map(int, input().split()))
	if arr == sorted(arr):
		answer = 0
		print(answer)
		return
	l = 0
	r = n - 1
	while l < n and arr[l] == l + 1:
		l += 1
	while r > -1 and arr[r] == r + 1:
		r -= 1
	while l <= r:
		if arr[l] == l + 1:
			answer = 2
			print(answer)
			return
		l += 1
	answer = 1
	print(answer)
t = int(input())
for _ in range(t):
	testcase()


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	f = sorted([i for (i, v) in enumerate(arr) if v != i + 1])
	if len(f) == 0:
		print(0)
		continue
	if f[-1] - f[0] + 1 == len(f):
		print(1)
		continue
	print(2)


import math
T = int(input().rstrip())

def check_contiguous_unsorted(arr):
	prev_state = arr[0]
	goo = 0 if prev_state == True else 1
	for i in range(1, len(arr)):
		curr_state = arr[i]
		if curr_state != prev_state:
			goo += 1
		prev_state = curr_state
	return goo <= 2

def solve(arr):
	sorted_arr = sorted(arr)
	num_sort_matches = 0
	is_in_sorted_pos = [False] * len(arr)
	for i in range(len(arr)):
		if sorted_arr[i] == arr[i]:
			is_in_sorted_pos[i] = True
			num_sort_matches += 1
	if num_sort_matches == len(arr):
		return 0
	elif num_sort_matches == 0:
		return 1
	elif check_contiguous_unsorted(is_in_sorted_pos):
		return 1
	return 2
for test in range(T):
	n = int(input().rstrip())
	arr = [int(x) for x in input().rstrip().split()]
	print(solve(arr))


import math
t = int(input())
cases = []
for i in range(t):
	input()
	cases.append(list(map(int, input().strip().split())))

def solve(case):
	intervals = 0
	right = True
	for i in range(len(case)):
		if i == case[i] - 1:
			right = True
		elif right:
			intervals += 1
			right = False
	if intervals == 0:
		print('0')
		return
	if intervals == 1:
		print('1')
		return
	else:
		print('2')
		return
for case in cases:
	solve(case)


import math as m
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	u = 0
	boo = False
	for i in range(n):
		if not boo and arr[i] != i + 1:
			u += 1
			boo = True
		elif arr[i] == i + 1:
			boo = False
	if u == 0:
		print(u)
	elif u == 1:
		print(1)
	else:
		print(2)


import math
from collections import defaultdict, deque
from sys import stdin
from bisect import bisect_left, bisect_right

def mp():
	return map(int, stdin.readline().split())

def ml():
	return list(map(int, stdin.readline().split()))
for _ in range(int(input())):
	n = int(input())
	a = ml()
	wc = 0
	for i in range(n):
		if i > 0 and a[i - 1] == i and (a[i] != i + 1) and (wc == 1):
			wc = 2
		if a[i] != i + 1 and wc == 0:
			wc = 1
	print(wc)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(s, e, f) = (0, 0, 0)
	for i in range(n):
		if a[i] != i + 1:
			break
		s += 1
	for i in range(n - 1, -1, -1):
		if a[i] != i + 1:
			break
		e += 1
	k = s
	while k < n - e:
		if a[k] == k + 1:
			f = 1
			break
		k += 1
	if s == n:
		print(0)
	elif f == 0:
		print(1)
	else:
		print(2)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		n = N()
		arr = RLL()
		sarr = sorted(arr)
		sm = 0
		tag = False
		for i in range(n - 1, -1, -1):
			if arr[i] == sarr[i] and tag == True:
				sm += 1
			if arr[i] != sarr[i]:
				tag = True
		if tag:
			for i in range(n):
				if arr[i] == sarr[i]:
					sm -= 1
				else:
					break
		if sm == 0:
			if tag == False:
				print(0)
			else:
				print(1)
		else:
			print(2)
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == [i + 1 for i in range(n)]:
		print(0)
		continue
	for i in range(n):
		if a[i] != i + 1:
			break
	for j in range(n - 1, -1, -1):
		if a[j] != j + 1:
			break
	for k in range(i, j + 1):
		if a[k] == k + 1:
			print(2)
			break
	else:
		print(1)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	ct = 1
	rflag = 1
	for i in range(n):
		if a[i] != i + 1:
			rflag = -1
			break
	if rflag == 1:
		print(0)
		continue
	else:
		rflag = 1
	maxtemp = a[0]
	for i in range(1, n):
		if a[i] == i + 1:
			if maxtemp != i:
				print(2)
				rflag = -1
				break
		maxtemp = max(maxtemp, a[i])
	if rflag == 1:
		print(1)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(lambda x: int(x) - 1, input().split()))
	l = -1
	r = -1
	for i in range(n):
		if arr[i] != i:
			if l == -1:
				l = i
			r = i + 1
	if l == -1:
		print(0)
		continue
	ans = 1
	for i in range(l, r):
		if arr[i] == i:
			ans = 2
	print(ans)


t = int(input())
while t > 0:
	size = int(input())
	inp = list(map(int, input().split()))
	start = []
	end = []
	flag = 0
	for i in range(size):
		if flag == 0 and inp[i] != i + 1:
			start.append(i + 1)
			flag = 1
		elif flag == 1 and inp[i] == i + 1:
			end.append(i)
			flag = 0
	temp = int(len(start))
	if temp < 2:
		print(temp)
	else:
		print(2)
	t -= 1


for _ in range(0, int(input())):
	j = int(input())
	l = list(map(int, input().strip().split()))
	r = 0
	index = []
	flag = 0
	length = 0
	for i in range(1, j + 1):
		if l[i - 1] == i:
			r += 1
			index.append(i)
			if r > 1:
				if index[-1] - 1 != index[-2]:
					flag = 1
	if r == j:
		print(0)
	elif r == 0:
		print(1)
	elif r == 1:
		if index[0] in [1, j]:
			print(1)
		else:
			print(2)
	elif flag == 0 and r != 1 and (index[0] in [1, j] or index[-1] in [1, j]):
		print(1)
	elif index[0] == 1 and index[-1] == j:
		flag9 = 0
		counter = 0
		while True:
			if flag9 == 1:
				if counter == j - 1:
					print(1)
					break
				else:
					print(2)
					break
			if index[counter] == counter + 1:
				counter += 1
			else:
				flag9 += 1
				counter = index[counter] - 1
	else:
		print(2)


import sys
input = sys.stdin.buffer.readline

def solution():
	for _ in range(int(input())):
		n = int(input())
		l = list(map(int, input().split()))
		x = n - 1
		while l[x] == x + 1 and x >= 0:
			x -= 1
		cnt = 0
		if x == -1:
			print(0)
		else:
			y = 0
			while l[y] == y + 1 and y < n:
				y += 1
			for i in range(y, x + 1):
				if l[i] != i + 1:
					cnt += 1
			if cnt == x - y + 1:
				print(1)
			else:
				print(2)
solution()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	for j in range(1, max(a) + 1):
		if j != a[j - 1]:
			break
	for k in range(max(a), 0, -1):
		if a[k - 1] != k:
			break
	v = 0
	for t in range(j, k + 1):
		if t == a[t - 1]:
			v += 1
	if v == 0 and j >= k:
		print(v)
	elif v == 0 and k > j:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	flag = 1
	for i in range(n):
		if a[i] == i + 1:
			b += [1]
		else:
			b += [0]
			flag = 0
	if flag:
		print(0)
	else:
		for i in range(n):
			if b[i] == 0:
				x = i
				break
		for i in range(len(b) - 1, -1, -1):
			if b[i] == 0:
				y = i
				break
		if sum(b[x:y + 1]) == 0:
			print(1)
		else:
			print(2)


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		n = iin()
		l = ain()
		flag = 0
		same = 0
		for i in range(1, n + 1):
			if i != l[i - 1]:
				if flag == 1 and same == 1:
					flag = 2
					break
				else:
					flag = 1
			elif flag == 1:
				same = 1
		if flag == 1:
			print(1)
		elif flag == 2:
			print(2)
		else:
			print(0)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = i = 0
	while i < n:
		if a[i] != i + 1:
			while i < n and a[i] != i + 1:
				i += 1
			ans += 1
		else:
			i += 1
	print(ans if ans < 2 else 2)


x = int(input())
for i in range(x):
	a = int(input())
	l = list(map(int, input().split()))
	c = l.copy()
	c.sort()
	if l == c:
		print(0)
	else:
		b = []
		for i in range(a):
			if l[i] != c[i]:
				b.append(i)
		for i in range(len(b) - 1):
			if b[i] + 1 != b[i + 1]:
				print(2)
				break
		else:
			print(1)


import sys
import math
import collections
from sys import stdin, stdout, setrecursionlimit
import bisect as bs
setrecursionlimit(2 ** 20)
M = 998244353
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	a = [0] + list(map(int, stdin.readline().split()))
	res = True
	b = []
	for i in range(1, n + 1):
		if a[i] == i:
			b.append(0)
			continue
		b.append(1)
		res = False
	if res:
		print(0)
		continue
	res = True
	don = False
	for i in range(n - 1):
		if b[i] == 1:
			if don:
				res = False
				break
		if b[i] == 1 and b[i + 1] == 0:
			don = True
	if b[-1] == 1 and don:
		res = False
	if res:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	idx = []
	for i in range(n):
		if i + 1 != l[i]:
			idx.append(i)
	if len(idx) == 0:
		print(0)
	elif len(idx) == max(idx) - min(idx) + 1:
		print(1)
	else:
		print(2)


for z in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	s = 1
	c = 0
	for i in range(n):
		if i + 1 != p[i]:
			if s:
				s = 0
				c += 1
		else:
			s = 1
	print(min(2, c))


from __future__ import division, print_function
from fractions import Fraction
import sys, bisect, heapq, copyreg, copy, statistics, os
from math import *
from collections import Counter, defaultdict, deque, OrderedDict
from itertools import combinations, permutations, accumulate
from bisect import bisect_left, bisect_right, bisect
from statistics import mode
from functools import reduce
from io import BytesIO, IOBase
from decimal import *
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def graph(vertex):
	return [[] for i in range(vertex + 1)]

def lcm(a, b):
	return a * b // gcd(a, b)

def most_frequent(List):
	return Counter(List).most_common(1)[0][0]

def most_common(List):
	return mode(List)

def chinese_remainder(a, p):
	prod = reduce(op.mul, p, 1)
	x = [prod // pi for pi in p]
	return sum((a[i] * pow(x[i], p[i] - 2, p[i]) * x[i] for i in range(len(a)))) % prod

def createMatrix(rowCount, colCount, dataList):
	mat = []
	for i in range(rowCount):
		rowList = []
		for j in range(colCount):
			if dataList[j] not in mat:
				rowList.append(dataList[j])
		mat.append(rowList)
	return mat

def readTree():
	v = int(inp())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	prime = []
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count

def digitsSum(n):
	if n == 0:
		return 0
	r = 0
	while n > 0:
		r += n % 10
		n //= 10
	return r

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def factors(n):
	return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return len(set(factors))

def prefixSum(arr):
	for i in range(1, len(arr)):
		arr[i] = arr[i] + arr[i - 1]
	return arr

def binomial_coefficient(n, k):
	if 0 <= k <= n:
		ntok = 1
		ktok = 1
		for t in range(1, min(k, n - k) + 1):
			ntok *= n
			ktok *= t
			n -= 1
		return ntok // ktok
	else:
		return 0

def powerOfK(k, max):
	if k == 1:
		return [1]
	if k == -1:
		return [-1, 1]
	result = []
	n = 1
	while n <= max:
		result.append(n)
		n *= k
	return result

def kadane(a, size):
	max_so_far = 0
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def divisors(n):
	result = []
	for i in range(1, ceil(sqrt(n)) + 1):
		if n % i == 0:
			if n / i == i:
				result.append(i)
			else:
				result.append(i)
				result.append(n / i)
	return result

def sumyilln(n):
	return n * (n + 1) // 2

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	for i in range(5, ceil(sqrt(n)) + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def isPowerOf2(n):
	while n % 2 == 0:
		n //= 2
	return True if n == 1 else False

def power2(n):
	k = 0
	while n % 2 == 0:
		k += 1
		n //= 2
	return k

def sqsum(n):
	return n * (n + 1) * (2 * n + 1) // 6

def cusum(n):
	return sumn(n) ** 2

def pa(a):
	for i in range(len(a)):
		print(a[i], end=' ')
	print()

def pm(a, rown, coln):
	for i in range(rown):
		for j in range(coln):
			print(a[i][j], end=' ')
		print()

def pmasstring(a, rown, coln):
	for i in range(rown):
		for j in range(coln):
			print(a[i][j], end='')
		print()

def isPerfectSquare(n):
	return pow(floor(sqrt(n)), 2) == n

def nC2(n, m):
	return n * (n - 1) // 2 % m

def modInverse(n, p):
	return pow(n, p - 2, p)

def ncrmodp(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def reverse(string):
	return ''.join(reversed(string))

def listtostr(s):
	return ' '.join([str(elem) for elem in s])

def binarySearch(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def isPalindrome(s):
	return s == s[::-1]

def gt(x, h, c, t):
	return (x * h + (x - 1) * c) / (2 * x - 1)

def CountFrequency(my_list):
	freq = {}
	for item in my_list:
		freq[item] = freq[item] + 1 if item in freq else 1
	return freq

def CountFrequencyasPair(my_list1, my_list2, freq):
	for item in my_list1:
		freq[item][0] = freq[item][0] + 1 if item in freq else 1
	for item in my_list2:
		freq[item][1] = freq[item][1] + 1 if item in freq else 1
	return freq

def binarySearchCount(arr, n, key):
	left = 0
	right = n
	mid = 0
	while left < right:
		mid = (right + left) // 2
		if arr[mid] == key:
			while mid + 1 < n and arr[mid + 1] == key:
				mid += 1
			break
		elif arr[mid] > key:
			right = mid
		else:
			left = mid + 1
	while mid > -1 and arr[mid] > key:
		mid -= 1
	return mid

def primes(n):
	(sieve, l) = ([True] * (n + 1), [])
	for p in range(2, n + 1):
		if sieve[p]:
			l.append(p)
			for i in range(p, n + 1, p):
				sieve[i] = False
	return l

def Next_Greater_Element_for_all_in_array(arr):
	(s, n, reta, retb) = (list(), len(arr), [], [])
	arr1 = [list([0, i]) for i in range(n)]
	for i in range(n - 1, -1, -1):
		while len(s) > 0 and s[-1][0] <= arr[i]:
			s.pop()
		if len(s) == 0:
			arr1[i][0] = -1
		else:
			arr1[i][0] = s[-1]
		s.append(list([arr[i], i]))
	for i in range(n):
		reta.append(list([arr[i], i]))
		retb.append(arr1[i][0])
	return (reta, retb)

class LRUCache:

	def __init__(self, capacity: int):
		self.cache = OrderedDict()
		self.capacity = capacity

	def get(self, key: int) -> int:
		if key not in self.cache:
			return -1
		else:
			self.cache.move_to_end(key)
			return self.cache[key]

	def put(self, key: int, value: int) -> None:
		self.cache[key] = value
		self.cache.move_to_end(key)
		if len(self.cache) > self.capacity:
			self.cache.popitem(last=False)
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def I():
	return inp()

def II():
	return int(inp())

def FI():
	return float(inp())

def SI():
	return list(str(inp()))

def MI():
	return map(int, inp().split())

def LI():
	return list(MI())

def MF():
	return map(float, inp().split())

def LF():
	return list(MF())
MOD = 10 ** 9 + 7
mod = 998244353
for _ in range(II()):
	n = II()
	a = LI()
	(c, d) = ([], [])
	if a == sorted(a):
		print(0)
		continue
	for i in range(n):
		if a[i] != i + 1:
			c.append(i)
	for i in range(len(c) - 1):
		d.append(c[i + 1] - c[i])
	print(1) if max(d) == min(d) == 1 else print(2)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator
from collections import deque, defaultdict, OrderedDict
import collections

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	zz = 0
	for _ in range(ri()):
		n = ri()
		a = ria()
		z = sorted(a)
		k = 0
		p = []
		for i in range(n):
			if a[i] != z[i]:
				k += 1
				p.append(0)
			else:
				p.append(1)
		if k == 0:
			print(0)
		elif k == n:
			print(1)
		else:
			t = 0
			(c, d) = (0, 0)
			p = [1] + p + [1]
			for i in range(n + 1):
				if p[i] == 1 and p[i + 1] == 0:
					t += 1
				if p[i] == 0 and p[i + 1] == 1:
					t += 1
			if t == 2:
				print(1)
			else:
				print(2)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	p = 0
	for i in range(n):
		if l[i] == i + 1:
			p += 1
	if p == n:
		print(0)
	elif p == 0:
		print(1)
	else:
		for i in range(n):
			if l[i] != i + 1:
				s = i
				break
		for i in range(n - 1, s, -1):
			if l[i] != i + 1:
				e = i
				break
		f = 0
		for i in range(s + 1, e):
			if l[i] == i + 1:
				f = 1
				break
		if f == 1:
			print(2)
		else:
			print(1)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	L = list(map(lambda x: int(x) - 1, input().split()))
	for i in range(n):
		if L[i] != i:
			break
	else:
		print(0)
		continue
	for j in range(i, n):
		if L[j] == j:
			break
	else:
		print(1)
		continue
	for k in range(j, n):
		if L[k] != k:
			break
	else:
		print(1)
		continue
	print(2)


def solve(n, a):
	i = 0
	while i < n and a[i] == i + 1:
		i += 1
	if i == n:
		return 0
	while i < n and a[i] != i + 1:
		i += 1
	if i == n:
		return 1
	while i < n and a[i] == i + 1:
		i += 1
	if i == n:
		return 1
	return 2
t = int(input())
for i_t in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	print(solve(n, a))


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	z = 1
	for i in range(n - 1):
		if ar[i + 1] <= ar[i]:
			z = 0
			break
	if z:
		print(0)
	else:
		(i, j) = (0, n - 1)
		while ar[i] == i + 1:
			i += 1
		while ar[j] == j + 1:
			j -= 1
		pos = 0
		for k in range(i, j + 1):
			if ar[k] == k + 1:
				pos = 1
		if pos:
			print(2)
		else:
			print(1)


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	j = n - 1
	while i < n:
		if a[i] == i + 1:
			i += 1
		else:
			break
	while j > 0:
		if a[j] == j + 1:
			j -= 1
		else:
			break
	if i > j:
		print(0)
		return
	while i < j:
		if a[i] == i + 1:
			print(2)
			return
		i += 1
	print(1)
	return
t = int(input())
for _ in range(t):
	solve()


t = int(input())
while t > 0:
	n = int(input())
	arr = [int(x) for x in input().split()]
	if arr == sorted(arr):
		print(0)
	else:
		firstUnsorted = 0
		while arr[firstUnsorted] == firstUnsorted + 1:
			firstUnsorted += 1
		lastUnsorted = len(arr) - 1
		while arr[lastUnsorted] == lastUnsorted + 1:
			lastUnsorted -= 1
		print2 = False
		for i in range(firstUnsorted, lastUnsorted + 1):
			if arr[i] == i + 1:
				print2 = True
				break
		if print2:
			print(2)
		else:
			print(1)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	p = 0
	for i in range(n):
		if x[i] == i + 1:
			p = p + 1
	if p == n:
		print(0)
	elif p == 0:
		print(1)
	else:
		start = 0
		end = n - 1
		for i in range(n):
			if x[i] != i + 1:
				start = i
				break
		for i in range(n - 1, -1, -1):
			if x[i] != i + 1:
				end = i
				break
		f = 1
		for i in range(start, end + 1):
			if x[i] == i + 1:
				f = 2
				break
		print(f)


import sys
import math
input = sys.stdin.readline

def inp():
	return int(input())

def inara():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
t = inp()
for _ in range(t):
	n = inp()
	ara = inara()
	l = 0
	while l < n and ara[l] == l + 1:
		l += 1
	r = n - 1
	while r >= 0 and ara[r] == r + 1:
		r -= 1
	if l > r:
		print(0)
	else:
		alada = 0
		for i in range(l, r + 1):
			if ara[i] == i + 1:
				alada += 1
		if alada:
			print(2)
		else:
			print(1)


t = int(input())
while t != 0:
	n = int(input())
	list1 = list(map(int, input().split()))
	if sorted(list1) == list1:
		print(0)
	else:
		i = 0
		while i + 1 == list1[i]:
			i += 1
		j = n - 1
		while j + 1 == list1[j]:
			j -= 1
		f = 0
		for k in range(i, j + 1):
			if list1[k] == k + 1:
				f = 1
				break
		if f == 1:
			print(2)
		else:
			print(1)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	r = []
	w = []
	for i in range(n):
		if arr[i] == i + 1:
			r += [i]
		else:
			w += [i]
	if not w:
		print(0)
	else:
		flag = 1
		for i in range(len(w) - 1):
			if w[i + 1] - w[i] != 1:
				print(2)
				flag = 0
				break
		if flag:
			print(1)


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	c = a.copy()
	c.sort()
	if c == a:
		print(0)
	else:
		b = []
		for i in range(len(a)):
			if a[i] != c[i]:
				b.append(i)
		for i in range(len(b) - 1):
			if b[i] + 1 != b[i + 1]:
				print(2)
				break
		else:
			print(1)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	count = 0
	matching = True
	for i in range(len(arr)):
		if arr[i] != i + 1:
			if matching:
				count += 1
			matching = False
		else:
			matching = True
	print(min(count, 2))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(first, end) = (-1, -1)
	hasNormal = False
	for i in range(n):
		if a[i] != i + 1:
			if first == -1:
				first = i
			end = i
	for i in range(first, end + 1):
		if a[i] == i + 1:
			hasNormal = True
	if first == -1:
		print(0)
	elif hasNormal:
		print(2)
	else:
		print(1)


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	n = iinput()
	a = rlinput()
	if sorted(a) == a:
		print(0)
		continue
	start = 0
	while start < n and a[start] == start + 1:
		start += 1
	end = n - 1
	while end >= 0 and a[end] == end + 1:
		end -= 1
	flag = False
	for i in range(start, end + 1):
		if a[i] == i + 1:
			flag = True
			break
	print([1, 2][flag])


def solve(n):
	s = list(map(int, input().split()))
	if s == sorted(s):
		return 0
	j = 0
	while s[j] == j + 1:
		j += 1
	k = n - 1
	while s[k] == k + 1:
		k -= 1
	for i in range(j, k + 1):
		if s[i] == i + 1:
			return 2
	return 1
for _ in range(int(input())):
	n = int(input())
	print(solve(n))


import math as mt
import sys, string
input = sys.stdin.readline
from collections import defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
t = I()
for _ in range(t):
	n = I()
	l = L()
	x = l[:]
	x.sort()
	c = 0
	f = 0
	for i in range(n):
		if x[i] != l[i] and f == 0:
			f = 1
			c += 1
		if x[i] == l[i]:
			f = 0
	if c == 0:
		print(0)
	elif c == 1:
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(enumerate(a, 1))
	c = [list(t) for t in b]
	for el in c:
		if el[0] == el[1]:
			el.append(0)
		else:
			el.append(1)
	d = ''
	for el in c:
		d += str(el[2])
	if set(d) == {'0'}:
		print(0)
	elif set(d) == {'1'}:
		print(1)
	elif d[0] == '0' and d.count('01') == 1:
		print(1)
	elif d[0] == '1' and d.count('01') == 0:
		print(1)
	else:
		print(2)


def find(A):
	change = []
	for i in range(len(A) - 1):
		if A[i] == i + 1 and A[i + 1] != i + 2:
			change += [i]
		elif A[i] != i + 1 and A[i + 1] == i + 2:
			change += [i]
	if len(change) == 1:
		return 1
	elif len(change) == 0:
		if A[i] == i + 1:
			return 0
		else:
			return 1
	elif len(change) == 2:
		if A[0] == 1:
			return 1
		else:
			return 2
	return 2
for _ in range(int(input())):
	input()
	A = list(map(int, input().strip().split()))
	print(find(A))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(_) for _ in input().split()]
	wrong = 0
	is_before_correct = True
	for i in range(n):
		idx = i + 1
		if a[i] == idx:
			is_before_correct = True
		else:
			if is_before_correct:
				wrong += 1
			else:
				pass
			is_before_correct = False
	if wrong > 2:
		print(2)
	else:
		print(wrong)


for x11 in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	k = 1
	count = 0
	ans = 0
	l1 = []
	flag = 0
	for x in l:
		if x != k:
			l1.append(1)
			flag = 1
		else:
			l1.append(0)
		k += 1
	if flag == 0:
		print(0)
	else:
		t = l1.index(1)
		t1 = len(l1) - l1[::-1].index(1)
		f = 0
		for x in range(t + 1, t1):
			if l1[x] == 0:
				f = 1
				break
		if f == 0:
			print(1)
		else:
			print(2)


from itertools import groupby
for _ in range(int(input())):
	(_, a) = (input(), list(map(int, input().split())))
	c = list(map(lambda x: x[0] == x[1], zip(a, sorted(a))))
	d = list(list(zip(*list(groupby(c))))[0])
	if all(c):
		print(0)
	elif d in [[True, False, True], [True, False], [False, True], [False]]:
		print(1)
	else:
		print(2)


t = int(input())
for T in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a1 = a[:]
	a1.sort()
	if a == a1:
		print(0)
		continue
	count = 0
	for i in range(n):
		if i > 0 and a[i - 1] == i and (a[i] != i + 1) and (count == 1):
			count = 2
		if a[i] != i + 1 and count == 0:
			count = 1
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	c = []
	for i in range(n):
		ch = i + 1
		if arr[i] == ch:
			c.append(0)
		else:
			c.append(1)
	ans = 0
	ct = False
	for i in range(n):
		if c[i] == 1:
			ct = True
		elif ct:
			ans += 1
			ct = False
	if ct:
		ans += 1
	if ans == 0:
		print(0)
	elif ans == 1:
		print(1)
	else:
		print(2)


import math
t = int(input())
for i in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	m = 0
	cc = 0
	mc = 0
	for j in range(0, n):
		if a[j] == j + 1:
			c = 1
			m = m + 1
			cc = 0
		else:
			cc = cc + 1
			if cc == 1:
				mc = mc + 1
	if c == 0 or mc == 1:
		print('1')
	elif m == n:
		print('0')
	else:
		print('2')


import sys
input = sys.stdin.readline
from collections import *
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	start = 0
	end = n
	for i in range(n):
		if a[i] == i + 1:
			start += 1
		else:
			break
	for i in range(n - 1, -1, -1):
		if a[i] == i + 1:
			end -= 1
		else:
			break
	ans = 1
	for i in range(start, end):
		if a[i] == i + 1:
			ans = 2
			break
	if start == n:
		ans = 0
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	persuit = sorted(arr)
	l = 0
	for i in range(n):
		if arr[i] != persuit[i]:
			l = i
			break
	else:
		print(0)
		continue
	r = 0
	for i in range(n - 1, -1, -1):
		if arr[i] != persuit[i]:
			r = i
			break
	for i in range(l, r + 1):
		if arr[i] == persuit[i]:
			print(2)
			break
	else:
		print(1)


from math import *
z = int(input())
for q in range(z):
	n = int(input())
	a = list(map(int, input().split()))
	b = a.copy()
	b.sort()
	if b == a:
		print(0)
	else:
		cnt = 1
		flag = 0
		flag1 = 0
		for i in range(n):
			if flag1 == 0 and a[i] != i + 1:
				flag1 = 1
			if a[i] == i + 1 and flag1 == 1:
				flag = 1
			if a[i] != i + 1 and flag == 1:
				flag = 0
				cnt = 2
		print(cnt)


import sys
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))
t = inp()
for _ in range(t):
	n = inp()
	a = inpl()
	if a == list(range(1, n + 1)):
		print(0)
		continue
	cnt = True
	fl = False
	ff = False
	for i in range(n):
		if ff:
			if i + 1 != a[i]:
				cnt = False
		elif fl:
			if i + 1 == a[i]:
				ff = True
		elif i + 1 != a[i]:
			fl = True
	print(1 if cnt else 2)


def is_sorted(A):
	for (i, a) in enumerate(A):
		if i + A[0] != a:
			return False
	return True

def ok_1(A):
	i = 0
	while i < len(A) and i + 1 == A[i]:
		i += 1
	while i < len(A) and i + 1 != A[i]:
		i += 1
	return is_sorted(A[i:])

def ans(A):
	if is_sorted(A):
		return 0
	if ok_1(A):
		return 1
	return 2
T = int(input())
for t in range(T):
	input()
	A = input().split(' ')
	A = list(map(int, A))
	print(ans(A))


t = int(input())
for x in range(t):
	n = int(input())
	arr = map(int, input().split(' '))
	count = 1
	group = False
	for (i, a) in enumerate(arr):
		if i == 0 and a == 1:
			group = True
			count -= 1
		else:
			if a == i + 1 and (not group):
				group = True
			if a != i + 1 and group:
				group = False
				count += 1
	if count > 2:
		print(2)
	else:
		print(count)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	x = 0
	a = 0
	b = 0
	for j in range(n):
		if l[j] != j + 1:
			if x == 0:
				a = j
			x += 1
			b = j
	if x:
		if b - a + 1 == x:
			print(1)
		else:
			print(2)
	else:
		print(0)


import math
from collections import deque
from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	cnt = 0
	bf = 0
	for i in range(n):
		if arr[i] == i + 1:
			if bf:
				bf = 0
		elif not bf:
			bf = 1
			cnt += 1
	print(min(cnt, 2))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	if a[0] == 1:
		l.append(1)
	else:
		l.append(0)
	for i in range(n):
		if a[i] == i + 1:
			if l[-1] == 1:
				continue
			else:
				l.append(1)
		elif l[-1] == 0:
			continue
		else:
			l.append(0)
	s = len(l)
	if s == 1:
		if l[0] == 1:
			print(0)
		else:
			print(1)
	elif s == 2:
		print(1)
	elif s == 3:
		if l[0] == 0:
			print(2)
		else:
			print(1)
	else:
		print(2)


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		total_displaced = 0
		lower = upper = lower2 = -1
		for (c, el) in enumerate(a):
			if el != c + 1:
				total_displaced += 1
				if lower == -1:
					lower = c
				elif upper != -1:
					lower2 = c
			elif lower != -1:
				upper = c - 1
		if total_displaced == n:
			print(1)
		elif total_displaced == 0:
			print(0)
		elif lower2 == -1:
			print(1)
		else:
			print(2)
main()


for _ in range(int(input())):
	i_liczb = int(input())
	liczby = [int(x) for x in input().split()]
	zla = False
	dobra = False
	zla2 = False
	for x in range(i_liczb):
		if dobra:
			if liczby[x] != x + 1:
				zla2 = True
				break
		if liczby[x] != x + 1:
			zla = True
			continue
		if zla:
			if liczby[x] == x + 1:
				dobra = True
				continue
	if zla == False:
		print(0)
	elif zla2 == False:
		print(1)
	else:
		print(2)


import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt, floor, factorial, gcd, log, ceil
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
import itertools

def Int():
	return int(sys.stdin.readline())

def Mint():
	return map(int, sys.stdin.readline().split())

def Lstr():
	return list(sys.stdin.readline().strip())

def Str():
	return sys.stdin.readline().strip()

def Mstr():
	return map(str, sys.stdin.readline().strip().split())

def List():
	return list(map(int, sys.stdin.readline().split()))

def Hash():
	return dict()

def Mod():
	return 1000000007

def Ncr(n, r, p):
	return fact[n] * (ifact[r] * ifact[n - r] % p) % p

def Most_frequent(list):
	return max(set(list), key=list.count)

def Mat2x2(n):
	return [List() for _ in range(n)]

def Lcm(x, y):
	lcm = x * y // gcd(x, y)
	return lcm

def solution():
	for i in range(Int()):
		n = Int()
		a = List()
		ans = []
		b = sorted(a)
		for i in range(n):
			if a[i] != b[i]:
				ans.append(i)
		if len(ans) == 0:
			print(0)
		else:
			c = 1
			for i in range(1, len(ans)):
				if ans[i] - ans[i - 1] != 1:
					c += 1
			if c > 2:
				print(2)
			else:
				print(c)
solution()


t = int(input())
for i in range(t):
	n = int(input())
	array = list(map(int, input().split()))
	j = n - 1
	i = 0
	count = 0
	while i <= n and j >= 0:
		if array[i] != i + 1 and array[j] != j + 1:
			break
		if array[j] == j + 1:
			j = j - 1
		if array[i] == i + 1:
			i = i + 1
	if i == n and j == -1:
		print(0)
	else:
		for k in range(i, j + 1):
			if array[k] == k + 1:
				count += 1
		if count == 0:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(p) for p in input().split()]
	i = 0
	j = n - 1
	while i < n and arr[i] == i + 1:
		i += 1
	while j >= 0 and arr[j] == j + 1:
		j -= 1
	if j < i:
		print(0)
		continue
	sub = arr[i:j + 1]
	cnt = 0
	for u in range(len(sub)):
		if sub[u] == i + u + 1:
			cnt += 1
			break
	if cnt:
		print(2)
	else:
		print(1)


import os
import heapq
import sys
import math
import bisect
import operator
from collections import defaultdict
from io import BytesIO, IOBase

def prime_factors(n):
	i = 2
	factors = set()
	while i * i <= n:
		if n % i:
			i += 1
		else:
			factors.add(n // i)
			n = n // i
			factors.add(i)
	if n > 1:
		factors.add(n)
	return factors

def isPrime(n):
	if n == 2 or n == 3:
		return True
	if n % 2 == 0 or n < 2:
		return False
	for i in range(3, int(n ** 0.5) + 1, 2):
		if n % i == 0:
			return False
	return True

def inar():
	return [int(k) for k in input().split()]

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcmm(a, b):
	return a * b // gcd(a, b)

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = inar()
		(res1, res2) = (0, 0)
		left = 10 ** 6
		right = 0
		counter = 0
		for i in range(n):
			if arr[i] != i + 1:
				left = min(left, i)
				right = max(right, i)
		if left == 10 ** 6 and right == 0:
			print(0)
			continue
		for i in range(n):
			if arr[i] == i + 1:
				if left < i < right:
					counter = 1
					break
		if counter:
			print(2)
		else:
			print(1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	n = int(input())
	a = [int(o) for o in input().split()]
	j = n
	while a and a[-1] == j:
		a.pop()
		j -= 1
	a = a[::-1]
	j = 1
	while a and a[-1] == j:
		a.pop()
		j += 1
	a = a[::-1]
	m = 0
	b = sorted(a)
	n = len(a)
	for i in range(n):
		if a[i] == b[i]:
			m += 1
	if m == n:
		print(0)
	elif m == 0:
		print(1)
	else:
		print(2)


def check(lis):
	ans = []
	for i in range(len(lis)):
		if i + 1 == lis[i]:
			ans.append(1)
		else:
			ans.append(0)
	return ans
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	s = check(lis)
	if sum(s) == n:
		print(0)
	else:
		for i in range(n - 1, 0, -1):
			if s[i] == 0:
				s = s[:i + 1]
				break
		k = 0
		for i in range(len(s)):
			if s[i] == 0:
				k = 1
			elif s[i] == 1:
				if k == 1:
					k = 2
					break
		print(k)


t = int(input())
import math
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	tip = 0
	lip = 0
	lf = True
	rip = 0
	rf = True
	i = 0
	while i < n:
		if a[i] == i + 1:
			tip += 1
		if a[i] == i + 1 and lf:
			lip += 1
		else:
			lf = False
		if a[n - 1 - i] == n - i and rf:
			rip += 1
		else:
			rf = False
		i += 1
	if tip == n:
		print(0)
	elif tip == lip + rip:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	l = -1
	case = 0
	sm = 0
	ans = 0
	for i in range(n):
		if arr[i] != i + 1 and l == -1:
			l = i
		if l != -1:
			sm += arr[i]
		if arr[i] == i + 1 and l != -1:
			case = 1
		if l != -1:
			t1 = (i + 1) * (i + 2) // 2
			t2 = l * (l + 1) // 2
			if t1 - t2 == sm:
				ans += 1 + case
				case = 0
				l = -1
				sm = 0
	print(min(ans, 2))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	last = True if l[0] == 1 else False
	cnt = 0 if l[0] == 1 else 1
	i = 2
	for x in l[1:]:
		if last != (x == i):
			cnt += 1
			last = False if last else True
		i += 1
	if cnt == 0:
		print(0)
	elif cnt <= 2:
		print(1)
	else:
		print(2)


t = int(input())
for _ in range(0, t):
	n = input()
	a = list(map(lambda x: int(x), input().split()))
	string = ''
	for i in range(0, len(a)):
		if a[i] == i + 1:
			string += '1'
		else:
			string += '0'
	string = string.strip('1')
	count_1 = string.count('1')
	if len(string) == 0:
		print(0)
	elif count_1 > 0:
		print(2)
	else:
		print(1)


def func(arr):
	flag = 0
	unsort = 0
	for i in range(len(arr)):
		if i + 1 == arr[i]:
			if unsort == 1:
				flag = 1
		else:
			unsort = 1
			if flag == 1:
				return 2
	return unsort
t = int(input())
for i in range(t):
	a = int(input())
	arr = list(map(int, input().split()))
	print(func(arr))


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	has_0 = False
	has_other = False
	start = 0
	while start < n and a[start] - start - 1 == 0:
		start += 1
	end = n - 1
	while end > -1 and a[end] - end - 1 == 0:
		end -= 1
	if start == n:
		print(0)
	else:
		for (i, v) in enumerate(a[start:end + 1], start=start):
			if abs(v - i - 1) == 0:
				has_0 = True
			else:
				has_other = True
		if has_0 and has_other:
			print(2)
		elif has_0:
			print(0)
		else:
			print(1)


def solve():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = list(map(int, input().split()))
		chk = [0] * n
		for (i, x) in enumerate(s):
			if i + 1 == x:
				chk[i] = 1
		cnt = 0
		chk.append(1)
		for i in range(n):
			if chk[i] == 0 and chk[i + 1] == 1:
				cnt += 1
		print(min(cnt, 2))
solve()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	if A == sorted(A):
		print(0)
	else:
		R = 0
		for (i, v) in enumerate(A):
			if i + 1 == v:
				if R == 1:
					R = 2
			elif R == 2:
				print(2)
				break
			else:
				R = 1
		else:
			print(1)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	if arr == sorted(arr):
		print(0)
	else:
		dp = [-1] * n
		corr = wrong = 0
		for i in range(n):
			if arr[i] == i + 1:
				dp[i] = 1
				corr += 1
			else:
				dp[i] = 0
				wrong += 1
		if wrong == n:
			print(1)
		else:
			start = dp.index(0)
			w1 = 0
			for i in range(start, n):
				if dp[i] == 0:
					w1 += 1
				else:
					break
			c1 = 0
			for i in range(start, n):
				if dp[i] == 1:
					c1 += 1
				else:
					break
			if w1 == wrong or c1 == corr:
				print(1)
			else:
				print(2)


from math import *
from collections import *
from bisect import *
import sys
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	same = 0
	indneed = []
	pre = []
	for i in range(n):
		if a[i] == i + 1:
			same += 1
		else:
			indneed.append(i + 1)
			pre.append(a[i])
	pre.sort()
	indneed.sort()
	if same == n:
		print(0)
		continue
	fuk = 0
	for i in range(indneed[0] - 1, indneed[-1]):
		if a[i] == i + 1:
			fuk = 1
	if same == 0 or (pre == indneed and fuk == 0):
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	ls = list(map(int, input().split()))
	mode = 0
	gis = 0
	for j in range(n):
		if mode == 0:
			if ls[j] != j + 1:
				mode = 1
				if gis == 1:
					break
		elif mode == 1:
			if ls[j] == j + 1:
				gis = 1
				mode = 0
	if mode == 1 and gis == 1:
		print(2)
	elif gis == 1 or mode == 1:
		print(1)
	else:
		print(0)


t = int(input())
while t:
	t -= 1
	n = int(input())
	l = list(map(int, input().split()))
	l.insert(0, 0)
	x = []
	c = 0
	for i in range(1, n + 1):
		if i != l[i]:
			x.append(i)
	if len(x) == 0:
		print(0)
	else:
		for i in range(1, len(x)):
			if x[i] - x[i - 1] > 1:
				c += 1
		if c > 0:
			print(2)
		else:
			print(1)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.insert(0, 0)
	c = 0
	el = []
	for i in range(1, n + 1):
		if l[i] == i:
			el.append(i)
			c += 1
	el.sort()
	if c == 0:
		print(1)
	elif c == n:
		print(0)
	else:
		if el and el[0] == 1:
			v = 1
			while 1:
				if not el:
					break
				if el[0] == v:
					del el[0]
					c -= 1
				else:
					break
				v += 1
		if el and el[c - 1] == n:
			v = n
			el.reverse()
			while 1:
				if not el:
					break
				if el[0] == v:
					del el[0]
					c -= 1
				else:
					break
				v -= 1
		if c == 0:
			print(1)
		else:
			print(2)


cases = int(input())
for t in range(cases):
	n = int(input())
	a = list(map(int, input().split()))
	v = list(range(1, n + 1))
	c = 0
	f = 0
	for i in range(n):
		if a[i] != v[i]:
			if f == 0:
				c += 1
				f = 1
		else:
			f = 0
	if c > 1:
		print(2)
	else:
		print(c)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	cou = 0
	b = []
	for i in range(n):
		if a[i] != i + 1:
			cou += 1
		else:
			if cou > 0:
				ans += 1
			cou = 0
	if cou > 0:
		ans += 1
	if ans == 0:
		print(0)
	elif ans == 1:
		print(1)
	else:
		print(2)


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import bisect as bi
import heapq

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def main():
	try:
		n = I()
		l = list(In())
		(pos1, pos2) = (-1, -1)
		for x in range(n):
			if l[x] != x + 1:
				if pos1 == -1:
					pos1 = x
				else:
					pos2 = x
		if pos1 == -1 and pos2 == -1:
			print(0)
		else:
			flag = 0
			for x in range(pos1, pos2 + 1):
				if l[x] == x + 1:
					flag = 1
					break
			if flag:
				print(2)
			else:
				print(1)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


t = int(input())
prev = 0
cont = 0
for _ in range(t):
	matched = 1
	count = 0
	index = 0
	m = input()
	a = list(map(int, input().split()))
	arr = [item for item in a]
	arr.sort()
	for i in range(len(arr)):
		index += 1
		if a[i] == arr[i]:
			count = 0
			if matched == 0:
				count = 2
				break
		else:
			matched = 0
			count = 1
	if count == 2 and index != len(arr):
		for index in range(index, len(arr)):
			if a[index] != arr[index]:
				count = 2
				break
			else:
				count = 1
	elif count == 2:
		count = 1
	print(count)


import math, itertools, fractions, heapq, collections, bisect, sys, queue, copy
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def LS():
	return sys.stdin.readline().split()

def S():
	return input()

def summarizeList(l):
	sl = l
	a = sl[0]
	c = 1
	res = []
	for x in sl[1:]:
		if x == a:
			c += 1
		else:
			res.append([a, c])
			a = x
			c = 1
	res.append([a, c])
	return res

def f(n):
	ret = 1
	for i in range(2, int(math.sqrt(n)) + 3):
		if n % i == 0:
			ret = max(ret, n // i, i)
	return ret

def main():
	n = I()
	ans = []
	for _ in range(n):
		k = I()
		l = LI()
		cnt = 0
		check = [0] * k
		for i in range(k):
			if i + 1 == l[i]:
				cnt += 1
				check[i] = 1
		if cnt == k:
			ans.append(0)
		elif cnt == 0:
			ans.append(1)
		else:
			sl = summarizeList(check)
			ff = 0
			for (x, c) in sl:
				if x == 0:
					ff += 1
			if ff == 1:
				ans.append(1)
			else:
				ans.append(2)
	for x in ans:
		print(x)
main()


tests = int(input())
for test in range(tests):
	n = int(input())
	a = [int(i) for i in input().split()]
	(l, r) = (-1, -1)
	ans = 1
	for i in range(n):
		if r == -1:
			if l == -1:
				if a[i] != i + 1:
					if l == -1:
						l = i
			elif a[i] == i + 1:
				if r == -1:
					r = i - 1
		elif a[i] != i + 1:
			ans = 2
			break
	if l == -1:
		print(0)
	else:
		print(ans)


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	N = getInt()
	A = [0] + getInts()
	targ = [j for j in range(N + 1)]
	if A == targ:
		return 0
	curr_index = 1
	curr_max = 0
	wrong = []
	while curr_index < N + 1:
		if A[curr_index] == curr_index:
			if curr_max > curr_index:
				return 2
		else:
			wrong.append(curr_index)
		curr_max = max(curr_max, A[curr_index])
		curr_index += 1
	if wrong[-1] - wrong[0] + 1 != len(wrong):
		return 2
	return 1
T = getInt()
for t in range(T):
	print(solve())


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
for _ in range(inp()):
	n = inp()
	x = ip()
	dp = [0] * n
	for i in range(n):
		if x[i] != i + 1:
			dp[i] = 1
	ct = 0
	prev = -1
	for i in range(n):
		if dp[i] == 1 and prev != 1:
			ct += 1
		prev = dp[i]
	if ct in [0, 1]:
		print(ct)
	else:
		print(2)


from math import *
from sys import *
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	cn = 0
	ch = 0
	for (i, j) in enumerate(a):
		if i + 1 == j and ch == 0:
			continue
		elif i + 1 == j and ch == 1:
			ch = 0
		elif i + 1 != j and ch == 0:
			cn += 1
			ch = 1
		else:
			continue
	if cn >= 2:
		cn = 2
	stdout.write(str(cn) + '\n')


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	if a == list(sorted(a)):
		print(0)
	else:
		count = 0
		(l, r) = (0, n - 1)
		while a[l] == l + 1:
			l += 1
		while a[r] == r + 1:
			r -= 1
		if l == n - 1 and r == 0:
			print(1)
		else:
			for i in range(l, r + 1):
				if a[i] == i + 1:
					count += 1
			if count > 0:
				print(2)
			else:
				print(1)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def mex(li):
	check = [0] * 1001
	for i in li:
		check[i] += 1
	for i in range(len(check)):
		if check[i] == 0:
			return i
from math import *
for _ in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	(i, ans) = (1, 0)
	while i <= n:
		if li[i - 1] != i:
			while li[i - 1] != i:
				i += 1
				if i == n + 1:
					break
			ans += 1
		else:
			i += 1
	if ans <= 1:
		print(ans)
	else:
		print(2)


def read_list():
	return list(map(int, input().split(' ')))

def print_list(l):
	print(' '.join(map(str, l)))
N = int(input())
for _ in range(N):
	n = int(input())
	nums = read_list()
	count = 0
	for i in range(n):
		if nums[i] == i + 1:
			count += 1
		else:
			break
	if count == n:
		print(0)
	else:
		tail = n
		for i in range(n - 1, -1, -1):
			if nums[i] != i + 1:
				break
			tail -= 1
		tmp = 0
		for i in range(count, tail):
			if nums[i] == i + 1:
				tmp += 1
				break
		print(tmp + 1)


t = int(input())
for _ in range(t):
	(n, c) = (int(input()), 0)
	ans = 0
	arr = [0] + list(map(int, input().split()))
	for i in range(1, n + 1):
		if i != arr[i]:
			c += 1
		else:
			ans += 1 if c else 0
			c = 0
	if c:
		ans += 1
	if ans == 0:
		print(0)
	elif ans == 1:
		print(1)
	else:
		print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	ar = []
	for i in range(n):
		if s[i] != i + 1:
			ar.append(i)
	if len(ar) == 0:
		print(0)
	else:
		bi = False
		for i in range(1, len(ar)):
			if ar[i] - ar[i - 1] != 1:
				bi = True
		if bi == True:
			print(2)
		else:
			print(1)


def solve(n, arr):
	temp = list.copy(arr)
	temp.sort()
	cnt = 0
	status = 0
	k = 0
	for i in range(0, n):
		if arr[i] != temp[i]:
			cnt += 1
			if status == 0:
				status = 1
		elif status == 1:
			status = 0
			k += 1
		if k > 1:
			print(2)
			return
	if status == 1:
		k += 1
	if k == 1:
		print(1)
	elif cnt == 0:
		print(0)
	elif cnt == n:
		print(1)
	else:
		print(2)
	pass
t = int(input())
for i in range(0, t):
	n = int(input())
	arr = list(map(int, input().split()))
	solve(n, arr)


for _ in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	li.append(n + 1)
	li1 = []
	count = 0
	can_count = False
	for i in range(len(li)):
		if li[i] - 1 == i:
			li1.append(0)
			if can_count:
				count += 1
				can_count = False
		else:
			li1.append(1)
			can_count = True
	if count > 1:
		print(2)
	elif count == 0:
		print(0)
	else:
		print(1)


T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	ans = 0
	cont = False
	for (i, a) in enumerate(A):
		if i + 1 != a:
			if not cont:
				ans += 1
				cont = True
		else:
			cont = False
	print(2 if ans >= 2 else ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	j = n - 1
	while i < n and a[i] == i + 1:
		i += 1
	while j > -1 and a[j] == j + 1:
		j -= 1
	if i <= j:
		s = 0
	else:
		s = -1
	for k in range(i, j + 1):
		if a[k] == k + 1:
			s += 1
	if s == -1:
		print(0)
	elif s == 0:
		print(1)
	else:
		print(2)


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def factorial(n):
	if n == 0:
		return 1
	return n * factorial(n - 1)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return len(set(factors))

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def factors(n):
	return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def printAllSubstrings(s, n):
	l = {}
	for i in range(n):
		temp = ''
		for j in range(i, n):
			temp += s[j]
			if temp not in l:
				l[temp] = 0
			l[temp] += 1
	return l
MOD = 1000000007
PMOD = 998244353
T = 1
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().rstrip().split()))
	isSorted = True
	for i in range(n - 1):
		if a[i + 1] < a[i]:
			isSorted = False
			break
	if isSorted:
		print(0)
		continue
	flag = True
	for p in range(n):
		if a[p] != p + 1:
			break
	for s in range(n - 1, -1, -1):
		if a[s] != s + 1:
			break
	for i in range(p, s + 1):
		if a[i] == i + 1:
			flag = False
			break
	if flag:
		print(1)
	else:
		print(2)


from collections import Counter, defaultdict, deque
import sys
input = sys.stdin.readline

def primes(n):
	arr = []
	nn = n
	d = 2
	while d * d <= nn and n != 1:
		if n % d == 0:
			arr.append(d)
			while n % d == 0:
				n //= d
		d += 1
	if n > 1:
		arr.append(n)
	return arr

def solve():
	n = int(input())
	arr = [int(x) for x in input().split()]
	if arr == sorted(arr):
		print(0)
	else:
		flag = False
		i = 0
		while arr[i] == i + 1:
			i += 1
		while i < n:
			if flag and arr[i] != i + 1:
				print(2)
				return
			if arr[i] == i + 1:
				flag = True
			i += 1
		print(1)
tt = int(input())
for test in range(tt):
	solve()


def cek(b, lis):
	bener = [i + 1 for i in range(b)]
	tru = []
	for i in range(b):
		if bener[i] == lis[i]:
			tru.append(1)
		else:
			tru.append(0)
	a = tru[0]
	ganti = 0
	for i in range(b - 1):
		if tru[i + 1] != tru[i]:
			ganti += 1
	if a == 0:
		if ganti == 1:
			return True
		else:
			return False
	if a == 1:
		if ganti == 1 or ganti == 2:
			return True
		else:
			return False
a = int(input())
for _ in range(a):
	b = int(input())
	awal = 1
	count = 0
	lis = list(map(int, input().split()))
	for i in lis:
		if i != awal:
			count += 1
		awal += 1
	if count == 0:
		print(0)
	elif count == b:
		print(1)
	elif cek(b, lis):
		print(1)
	else:
		print(2)


t = int(input())
while t:
	t = t - 1
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	sorted = 0
	for i in range(n):
		if a[i] == i + 1:
			sorted += 1
		else:
			b.append(i + 1)
	if sorted == n:
		print(0)
	elif sorted != n:
		minb = min(b)
		maxb = max(b)
		rangeuns = maxb - minb + 1
		unsorted = n - sorted
		if unsorted == rangeuns:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	(*arr,) = map(int, input().split())
	cnt = 0
	start = -1
	end = -1
	for (i, v) in enumerate(arr):
		if i != v - 1:
			if start == -1:
				start = i
		elif start != -1:
			cnt += 1
			start = -1
	if start != -1:
		cnt += 1
	if cnt == 0:
		print(0)
	elif cnt == 1:
		print(1)
	else:
		print(2)


from collections import Counter
import string
import math
import sys
from fractions import Fraction

def array_int():
	return [int(i) for i in sys.stdin.readline().split()]

def vary(arrber_of_variables):
	if arrber_of_variables == 1:
		return int(sys.stdin.readline())
	if arrber_of_variables >= 2:
		return map(int, sys.stdin.readline().split())

def makedict(var):
	return dict(Counter(var))

def printDivisors(n):
	divisors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				divisors.append(i)
			else:
				divisors.extend((i, n // i))
		i = i + 1
	return divisors

def countTotalBits(num):
	binary = bin(num)[2:]
	return len(binary)

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
for _ in range(vary(1)):
	n = vary(1)
	num = array_int()
	mark = [0 for i in range(n)]
	for i in range(n):
		if num[i] != i + 1:
			mark[i] = 1
	count = 0
	flag = 1
	for i in range(n):
		if mark[i] == 1:
			if i == n - 1:
				count += 1
			flag = 0
			continue
		elif flag != 1:
			flag = 1
			count += 1
	if count > 2:
		print(2)
	else:
		print(count)


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for _ in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(n, a):
	count = 0
	mixed = []
	for (i, item) in enumerate(a):
		if item == i + 1:
			count += 1
		else:
			mixed.append(i)
	if count == n:
		return 0
	elif count == 0:
		return 1
	for i in range(1, len(mixed)):
		if mixed[i] != mixed[i - 1] + 1:
			return 2
	return 1
for _ in tests():
	n = int_in()
	a = arr_in()
	out(solve(n, a))


T = int(input())
while T > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	x = []
	for i in range(n):
		if arr[i] != i + 1:
			x.append(i)
	if len(x) == 0:
		print(0)
	elif x[-1] - x[0] + 1 == len(x):
		print(1)
	else:
		print(2)
	T -= 1


from math import *
from collections import *
from operator import itemgetter
import bisect
from heapq import *
i = lambda : input()
ii = lambda : int(input())
iia = lambda : list(map(int, input().split()))
isa = lambda : list(input().split())
I = lambda : list(map(int, input().split()))
chrIdx = lambda x: ord(x) - 96
idxChr = lambda x: chr(96 + x)
t = ii()
for _ in range(t):
	n = ii()
	a = iia()
	b = [i + 1 for i in range(n)]
	c = []
	for i in range(n):
		c.append(a[i] - (i + 1))
	i = 0
	cnt1 = 0
	while i < n:
		if c[i] == 0:
			j = i + 1
			while j < n:
				if c[j] == 0:
					j += 1
				else:
					break
			i = j
		else:
			cnt1 += 1
			j = i + 1
			while j < n:
				if c[j] != 0:
					j += 1
				else:
					break
			i = j
	cnt = c.count(0)
	if cnt == n:
		print(0)
	elif cnt == 0 or cnt1 <= 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	for i in l:
		l1.append(i)
	l1.sort()
	if l == l1:
		print(0)
	else:
		(f, cnt) = (0, 0)
		for i in range(n):
			if l[i] != i + 1:
				f = 1
			else:
				if f == 1:
					cnt += 1
				f = 0
		if f == 1:
			cnt += 1
		print(min(2, cnt))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	(count, index) = (0, 0)
	if arr == sorted(arr):
		print(0)
		continue
	while index < n:
		if arr[index] == index + 1:
			index += 1
			continue
		count += 1
		while index < n and arr[index] != index + 1:
			index += 1
	if count == 1:
		print(1)
	else:
		print(2)


t = int(input())
for hatt in range(t):
	n = int(input())
	a = [int(num) for num in input().split()]
	coun = 0
	if a[0] == 1:
		prev = True
	else:
		coun = 1
		prev = False
	for i in range(1, n):
		if a[i] == i + 1:
			prev = True
		else:
			if prev:
				coun += 1
			prev = False
	print(min(coun, 2))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.insert(0, 0)
	start = False
	c = 0
	for i in range(1, n + 1):
		if i != a[i] and start == False:
			start = True
			c += 1
		if i == a[i] and start == True:
			start = False
	if c < 2:
		print(c)
	else:
		print(2)


import os
from sys import stdin, stdout

def solve(tc):
	n = int(stdin.readline().strip())
	seq = list(map(int, stdin.readline().split()))
	notok = []
	for i in range(n):
		if seq[i] != i + 1:
			notok.append(i)
	if len(notok) == 0:
		print(0)
	elif notok[-1] - notok[0] + 1 == len(notok):
		print(1)
	else:
		print(2)
tcs = 1
tcs = int(stdin.readline().strip())
tc = 1
while tc <= tcs:
	solve(tc)
	tc += 1


from collections import Counter
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()
for _ in range(t):
	(n,) = gil()
	a = gil()
	for i in range(n):
		a[i] -= 1
	p = 0
	ans = 0
	while p < n:
		lmt = a[p]
		flag = True if p == a[p] else False
		start = p
		while p <= lmt:
			lmt = max(a[p], lmt)
			flag |= a[p] == p
			p += 1
		if flag:
			if start != p - 1:
				ans += 2
		else:
			ans += 1
	print(min(2, ans))


num_test_case = int(input())
for case in range(num_test_case):
	n = int(input())
	num_list = list(map(int, input().split()))
	id_list = list(range(1, n + 1))
	dif_list = []
	for i in range(n):
		dif_list.append(id_list[i] - num_list[i])
	edgeZeroCounter = 0
	for num in dif_list:
		if num == 0:
			edgeZeroCounter += 1
		else:
			break
	for num in reversed(dif_list):
		if num == 0:
			edgeZeroCounter += 1
		else:
			break
	fixedPointCounter = 0
	for num in dif_list:
		if num == 0:
			fixedPointCounter += 1
	if fixedPointCounter == n:
		answer = 0
	elif fixedPointCounter == 0 or fixedPointCounter == edgeZeroCounter:
		answer = 1
	else:
		answer = 2
	print(answer)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = 0
	r = n
	i = 0
	while i < n and a[i] == i + 1:
		l += 1
		i += 1
	i = n - 1
	while i >= 0 and a[i] == i + 1:
		r -= 1
		i -= 1
	b = [a[i] for i in range(l, r) if a[i] != i + 1]
	if len(b) == 0:
		print(0)
	elif len(b) == r - l:
		print(1)
	else:
		print(2)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	n = val()
	l = li()
	index = {}
	tot = 0
	for i in range(n):
		index[l[i]] = i
		tot += l[i] == i + 1
	if l == sorted(l):
		print(0)
		continue
	if tot == 0:
		print(1)
		continue
	i = 1
	while index[i] == i - 1:
		tot -= 1
		i += 1
	j = n
	while index[j] == j - 1:
		tot -= 1
		j -= 1
	if tot > 0:
		print(2)
	else:
		print(1)


import sys
input = sys.stdin.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		bad = [0] * n
		found = False
		for i in range(n):
			if a[i] != i + 1:
				bad[i] = 1
				found = True
		if not found:
			print(0)
		else:
			components = 0
			if bad[0] == 1:
				components += 1
			for i in range(n - 1):
				if bad[i] == 0 and bad[i + 1] == 1:
					components += 1
					if components == 2:
						break
			if components == 1:
				print(1)
			else:
				print(2)
prog()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = 0
	marker = 0
	for i in range(n):
		if arr[i] != i + 1 and marker == 0:
			marker = 1
			ans += 1
		elif arr[i] == i + 1 and marker == 1:
			marker = 0
	print(min(ans, 2))


def check(a):
	l = 0
	r = 0
	for i in range(n):
		if a[i] != i + 1:
			l = i
			break
	for j in range(n - 1, -1, -1):
		if a[j] != j + 1:
			r = j
			break
	for i in range(l, r + 1):
		if a[i] == i + 1:
			return 1
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split(' ')))
	if a == sorted(a):
		print(0)
	elif check(a) == 1:
		print(2)
	else:
		print(1)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if l == sorted(l):
		print(0)
	else:
		(x, y, f) = (1, n, 0)
		for i in range(n):
			if l[i] != x:
				break
			x += 1
		for i in range(n):
			if l[n - i - 1] != y:
				break
			y -= 1
		for i in range(x - 1, y - 1):
			if l[i] == i + 1:
				f = 1
		if f == 1:
			print(2)
		else:
			print(1)


x = int(input())
for t in range(x):
	y = int(input())
	arr = list(map(int, input().split()))
	a = 0
	l = 0
	ar = []
	while a < len(arr):
		if arr[a] == a + 1:
			l += 1
			ar.append(arr[a])
		a += 1
	if l == len(arr):
		print(0)
	elif l == 0:
		print(1)
	else:
		a = 0
		while a < len(ar) and ar[a] == a + 1:
			a += 1
		a -= 1
		b = len(ar) - 1
		i = 0
		while b >= 0 and ar[b] == arr[-1 - i]:
			b -= 1
			i += 1
		b += 1
		if b - a == 1:
			print(1)
		else:
			print(2)


from sys import stdout, stdin
(_input, _print) = (stdin.readline, stdout.write)
(_range, _sorted, _int) = (range, sorted, int)

def solution():
	for _ in _range(_int(_input())):
		n = _int(_input())
		arr = [_int(i) for i in _input().split()]
		sorted_arr = _sorted(arr)
		(l, r) = (0, n - 1)
		while l < r:
			if arr[l] == sorted_arr[l]:
				l += 1
			elif arr[r] == sorted_arr[r]:
				r -= 1
			else:
				break
		if l >= r:
			print(0)
			continue
		c = 0
		for i in _range(l, r + 1):
			if arr[i] == sorted_arr[i]:
				c += 1
		if c == 0:
			print(1)
		else:
			print(2)
solution()


def modinv(n, p):
	return pow(n, p - 2, p)

def main():
	for case in range(int(input())):
		n = int(input())
		a = [int(x) for x in input().split()]
		b = [x for x in a]
		b.sort()
		t = []
		for i in range(n):
			if a[i] == b[i]:
				t.append(0)
			else:
				t.append(1)
		c = t.count(1)
		if c == 0:
			print(0)
		else:
			inds = []
			for i in range(n):
				if t[i] == 1:
					inds.append(i)
			inds.sort()
			two_flag = False
			for i in range(len(inds) - 1):
				if abs(inds[i + 1] - inds[i]) > 1:
					two_flag = True
					break
			if two_flag:
				print(2)
			else:
				print(1)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin as cin
from itertools import groupby
from operator import eq
lmap = lambda f, v: list(map(f, v))

def main():
	t = int(next(cin).strip())
	for i in range(t):
		n = int(next(cin).strip())
		a = lmap(int, next(cin).strip().split())
		inplace = [inplace for (inplace, _) in groupby((i == ai for (i, ai) in enumerate(a, 1)))]
		if inplace == [True]:
			print(0)
		elif len(inplace) < 3 or inplace == [True, False, True]:
			print(1)
		else:
			print(2)
main()


import sys, io, os, time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
input = sys.stdin.readline
for ii in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = 0
	ok1 = True
	ok2 = True
	fw = n
	lw = 0
	for i in range(1, n + 1):
		if arr[i - 1] != i:
			ok1 = False
			fw = min(fw, i)
			lw = max(lw, i)
	for i in range(fw, lw + 1):
		if arr[i - 1] == i:
			ok2 = False
	if ok1:
		print(0)
	elif ok2:
		print(1)
	else:
		print(2)


t = int(input())
while t:
	t += -1
	n = int(input())
	l = list(map(int, input().split()))
	cnt = 0
	tmp = []
	for i in range(n):
		if l[i] == i + 1:
			cnt -= -1
		else:
			tmp.append(i)
	if cnt == 0:
		print(1)
	elif cnt == n:
		print(0)
	else:
		check = 1
		for i in range(1, len(tmp)):
			if tmp[i] != tmp[i - 1] + 1:
				check = 0
				break
		if check:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = 0
	s = 1
	for i in range(n):
		if arr[i] != i + 1:
			if s:
				s = 0
				ans += 1
		else:
			s = 1
	print(min(ans, 2))


t = int(input())
for _ in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	active = False
	counter = 0
	wc = []
	flag = False
	for i in range(len(nums)):
		if active:
			if i + 1 != nums[i]:
				if counter > 0:
					flag = True
			elif i + 1 == nums[i]:
				counter += 1
		elif i + 1 != nums[i]:
			active = True
	if active is False:
		print(0)
	elif flag is False:
		print(1)
	elif flag is True:
		print(2)


import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
	N = int(input())
	A = [int(_) for _ in input().split()]
	one_bad = False
	one_good = False
	next_bad_2 = False
	bad_2 = False
	for (i, el) in enumerate(A):
		if i + 1 == el:
			one_good = True
			if one_bad:
				next_bad_2 = True
		else:
			one_bad = True
			if next_bad_2:
				bad_2 = True
	if not one_bad:
		print(0)
	elif one_good and bad_2:
		print(2)
	else:
		print(1)


t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	a = sorted(arr)
	if arr == a:
		print(0)
	else:
		f = []
		for i in range(n):
			if arr[i] != i + 1:
				f.append(i)
		if len(f) == 0:
			print(0)
		else:
			f.sort()
			if len(f) == f[-1] - f[0] + 1:
				print(1)
			else:
				print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	(c, m) = (0, 0)
	c_arr = [0 for _ in range(n)]
	a = [int(e) - 1 for e in input().split()]
	for i in range(n):
		if a[i] == i:
			c_arr[i] = 1
			c = c + 1
	if c != n:
		(left, right) = (0, 0)
		while a[left] == left:
			left = left + 1
		while a[n - right - 1] == n - right - 1:
			right = right + 1
	if c == n:
		ans = 0
	elif c == 0 or c == left + right:
		ans = 1
	else:
		ans = 2
	print(ans)


from sys import *
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	l.insert(0, 0)
	for i in range(1, n + 1):
		if i != l[i] and i - 1 == l[i - 1]:
			c += 1
	if c == 0 or c == 1:
		print(c)
	else:
		print(2)


from sys import stdin
import math
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	if a == list(range(1, n + 1)):
		print(0)
		continue
	l = 0
	h = n
	notZero = False
	for i in range(n):
		if a[i] == i + 1:
			l += 1
		else:
			break
	for i in range(n - 1, -1, -1):
		if a[i] == i + 1:
			h -= 1
		else:
			break
	for i in range(l, h):
		if a[i] == i + 1:
			print(2)
			break
	else:
		print(1)


tt = int(input())
for loop in range(tt):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	for i in range(n):
		if a[i] != i + 1 and cnt % 2 == 0:
			cnt += 1
		elif a[i] == i + 1 and cnt % 2 == 1:
			cnt += 1
	if cnt == 0:
		print(0)
	elif cnt <= 2:
		print(1)
	else:
		print(2)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	i = 0
	j = n - 1
	l = -1
	r = n
	while i < n:
		if arr[i] != i + 1:
			l = i
			break
		i += 1
	while j >= 0:
		if arr[j] != j + 1:
			r = j
			break
		j -= 1
	temp = arr[l:r + 1]
	if l == -1 and r == n:
		print(0)
		continue
	if l + 1 == r:
		print(1)
		continue
	i = 0
	ct = 0
	while i < r - l + 1:
		if temp[i] == i + l + 1:
			ct += 1
		i += 1
	if ct == 0:
		print(1)
	else:
		print(2)


def trim_start(xs):
	i = 0
	while i < len(xs):
		if xs[i] != i + 1:
			return (xs[i:], i)
		i += 1
	return (xs[i:], i)

def trim_end(xs):
	i = len(xs)
	while i > 0:
		if xs[i - 1] != i:
			return xs[:i]
		i -= 1
	return xs[:i]

def in_place_count(xs, offset):
	count = 0
	for (i, v) in enumerate(xs):
		if i + 1 + offset == v:
			count += 1
	return count

def solve(xs):
	xs = trim_end(xs)
	(xs, offset) = trim_start(xs)
	if len(xs) == 0:
		return 0
	count = in_place_count(xs, offset)
	if count == 0:
		return 1
	else:
		return 2
assert solve([3, 2, 4, 5, 1, 6, 7]) == 2
assert solve([1, 5, 3, 4, 2, 6]) == 2
assert solve(list(map(int, '1 5 3 4 6 2'.split(' ')))) == 2
assert solve([2, 3, 1]) == 1

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		xs = list(map(int, input().split(' ')))
		print(solve(xs))
main()


import math

def mi():
	return map(int, input().split())

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def si():
	return input().split()
t = ii()
for _ in range(t):
	n = ii()
	a = li()
	if a == sorted(a):
		print(0)
	else:
		i = 0
		cnt = 0
		while i < n:
			while i < n and a[i] == i + 1:
				i += 1
			if i >= n:
				break
			while i < n and a[i] != i + 1:
				i += 1
			cnt += 1
		print(min(cnt, 2))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	nm = []
	for i in range(0, n):
		if a[i] - 1 != i:
			nm.append(i)
	if len(nm) == 0:
		print(0)
	else:
		b = len(nm)
		fg = 0
		for i in range(1, b):
			if nm[i] != nm[i - 1] + 1:
				fg = 1
				break
		if fg == 0:
			print(1)
		else:
			print(2)


import math
import os
import random
import re
import sys
from collections import Counter

def solve():
	for _ in range(int(input())):
		n = int(input())
		l = list(map(int, input().strip().split()))
		ft = [True] * n
		for i in range(n):
			if l[i] == i + 1:
				continue
			else:
				ft[i] = False
		if ft.count(True) == n:
			print(0)
			continue
		elif ft.count(False) == n:
			print(1)
			continue
		(st, end) = (0, n - 1)
		for i in range(n):
			if ft[i] == True:
				continue
			else:
				st = i
				break
		for i in range(n - 1, -1, -1):
			if ft[i] == True:
				continue
			else:
				end = i
				break
		c = ft[st:end + 1].count(True)
		if c > 0:
			print(2)
		else:
			print(1)
solve()


import sys
import heapq
input = lambda : sys.stdin.readline().strip()
ipnut = input
pprint = lambda x: print(' '.join(map(lambda t: str(t + 1), x)))

def mex():
	used = set(a)
	for i in range(n + 1):
		if i not in used:
			return i
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(l, r) = (0, n - 1)
	while l < r and a[l] == l + 1:
		l += 1
	while r > l and a[r] == r + 1:
		r -= 1
	ans = 0
	for i in range(l, r):
		ans = 1
		if a[i] == i + 1:
			ans = 2
			break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().strip().split(' ')))
	uni = True
	uc = 0
	for i in range(n):
		if i + 1 == arr[i]:
			uni = False
			uc += 1
	if uni:
		print(1)
	elif uc == n:
		print(0)
	else:
		i = 0
		sc = 0
		while i < n:
			if arr[i] != i + 1:
				sc += 1
				while i < n and arr[i] != i + 1:
					i += 1
			else:
				i += 1
		if sc == 1:
			print(1)
		else:
			print(2)


t = int(input())

def solve(n, arr):
	f = False
	end = False
	if arr == [i for i in range(1, n + 1)]:
		return 0
	for (i, a) in enumerate(arr, 1):
		if end and i != a:
			return 2
		if i == a and (not f):
			pass
		elif i == a and f:
			end = True
		elif i != a and f:
			continue
		else:
			f = True
	return 1
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(solve(n, arr))


from sys import stdin, stdout
import math
from collections import Counter, defaultdict
LI = lambda : list(map(int, input().split()))
MAP = lambda : map(int, input().split())
IN = lambda : int(input())
S = lambda : input()

def case():
	n = IN()
	a = LI()
	x = []
	c0 = c1 = 0
	for i in range(n):
		if i + 1 == a[i]:
			x.append(1)
			c1 += 1
		else:
			x.append(0)
			c0 += 1
	if c0 == n:
		print(1)
		return
	elif c1 == n:
		print(0)
		return
	while len(x) and x[0] != 0:
		x.pop(0)
	while len(x) and x[-1] == 1:
		x.pop()
	if sum(x):
		print(2)
	else:
		print(1)
for _ in range(IN()):
	case()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	chk = 0
	f = 0
	s = 0
	b = n
	for i in range(n):
		if arr[i] == i + 1:
			s += 1
		else:
			break
	for i in range(n - 1, -1, -1):
		if arr[i] == i + 1:
			b -= 1
		else:
			break
	if s == n or b == 0:
		print('0')
	else:
		for i in range(s, b):
			if arr[i] != i + 1:
				chk = 1
			if arr[i] == i + 1:
				f = 1
		if f == 1 and chk == 0:
			print('0')
		if f == 0 and chk == 1:
			print('1')
		if f == 1 and chk == 1:
			print('2')


import math
from collections import Counter, deque, defaultdict
L = lambda : list(map(int, input().split()))
M = lambda : map(int, input().split())
I = lambda : int(input())
IN = lambda : input()
mod = 10 ** 9 + 7

def s(a):
	print(''.join(list(map(str, a))))

def solve():
	n = I()
	a = L()
	b = []
	for i in range(n):
		if a[i] == i + 1:
			b += [1]
		else:
			b += [0]
	if 0 not in b:
		print(0)
		return
	for i in range(n):
		if b[i] == 0:
			x = i
			break
	for i in range(len(b) - 1, -1, -1):
		if b[i] == 0:
			y = i
			break
	if sum(b[x:y + 1]) == 0:
		print(1)
	else:
		print(2)
for _ in range(I()):
	solve()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	f = 1
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			f = 0
	if f == 1:
		print(0)
	else:
		g = 0
		cnt = 0
		l = 0
		for i in range(n):
			if arr[i] == i + 1:
				cnt += 1
			else:
				if cnt != 0 and l != 0:
					g += 1
				cnt = 0
				l = i + 1
		if g != 0:
			print(2)
		else:
			print(1)


from sys import stdin
for _ in range(int(input())):
	n = int(stdin.readline().rstrip())
	l = list(map(int, stdin.readline().rstrip().split(' ')))
	if l == sorted(l):
		print(0)
	else:
		cs = ce = 0
		for i in range(0, n):
			if l[i] != i + 1:
				break
			cs += 1
		for i in range(n - 1, -1, -1):
			if l[i] != i + 1:
				break
			ce += 1
		pos_al_sorted = False
		for i in range(cs, n - ce):
			if l[i] == i + 1:
				pos_al_sorted = True
				break
		if pos_al_sorted:
			print(2)
		else:
			print(1)


def solve():
	N = int(input())
	A = [int(x) for x in input().split()]
	ans = 0
	for i in range(N - 1):
		if A[i] > A[i + 1]:
			ans = -1
	if ans == 0:
		print(ans)
		return
	x = []
	for i in range(N):
		if A[i] != i + 1:
			x.append(i)
	ans = 1
	for i in range(len(x) - 1):
		if x[i] != x[i + 1] - 1:
			ans = 2
	print(ans)

def main():
	T = int(input())
	while T != 0:
		solve()
		T -= 1
main()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	s = a[:]
	s.sort()
	arr = [[]]
	if a == s:
		print(0)
	else:
		for i in range(len(a)):
			if a[i] != s[i]:
				arr[-1].append(a[i])
			elif len(arr[-1]) != 0:
				arr.append([])
			if len(arr) >= 4:
				break
		if len(arr) == 1 or len(arr) - arr.count([]) == 1:
			print(1)
		else:
			print(2)


for t in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split(' ')]
	l1 = sorted(l)
	if l == l1:
		print(0)
		continue
	s = []
	for i in range(n):
		if l[i] == i + 1:
			s.append(1)
		else:
			s.append(0)
	while s[-1] == 1:
		s = s[:-1]
	while s[0] == 1:
		s = s[1:]
	if 1 in s:
		print(2)
	else:
		print(1)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	count = 0
	flag = 0
	for i in range(n):
		if arr[i] != i + 1:
			flag = 1
		elif flag == 1:
			flag = 0
			count += 1
	if flag == 1:
		count += 1
	if count == 0:
		print(0)
	elif count == 1:
		print(1)
	else:
		print(2)


def sol():
	am = int(input())
	arr = list(map(int, input().split()))
	if arr == list(range(1, am + 1)):
		print(0)
		return 0
	fl = False
	itsOk = True
	l = 0
	for i in range(am):
		if arr[i] - 1 != i:
			if fl == False:
				l = i
				fl = True
			elif l + 1 != i:
				itsOk = False
				break
			else:
				l = i
	if itsOk:
		print(1)
	else:
		print(2)
for _ in range(int(input())):
	sol()


t = int(input())

def is_block(a):
	run = False
	flag = False
	for (i, x) in enumerate(a):
		if x != i + 1:
			if not run and flag:
				return False
			if not run and (not flag):
				run = True
				continue
			run = True
		elif run:
			flag = True
			run = False
	return True
for case in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	if all((x == i + 1 for (i, x) in enumerate(a))):
		print(0)
		continue
	if is_block(a):
		print(1)
	else:
		print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	wrongcount = 0
	for i in range(n):
		if i > 0 and a[i - 1] == i and (a[i] != i + 1) and (wrongcount == 1):
			wrongcount = 2
		if a[i] != i + 1 and wrongcount == 0:
			wrongcount = 1
	print(wrongcount)


n = int(input())
for i2 in range(n):
	x = int(input())
	l = list(map(int, input().split()))
	p = 0
	p1 = 0
	p2 = 0
	k = 0
	for i in range(x):
		if l[i] == i + 1:
			p1 += 1
		else:
			break
	for i in range(x - 1, -1, -1):
		if l[i] == i + 1:
			p2 += 1
		else:
			break
	for i in range(p1, x - p2):
		if l[i] == i + 1:
			p += 1
	if p1 == x:
		print(0)
	elif p == 0:
		print(1)
	else:
		print(2)


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	(N,) = map(int, input().split())
	X = list(map(int, input().split()))
	f = 1
	fc = 0
	for i in range(N):
		if X[i] != i + 1:
			if f:
				fc += 1
			f = 0
		else:
			f = 1
	if fc == 0:
		print(0)
	elif fc == 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	tt = [*map(int, input().split())]
	if tt == sorted(tt):
		print(0)
		continue
	(xx, l, r) = (0, 0, 0)
	for i in range(n):
		if i + 1 != tt[i]:
			l = i
			break
	for i in range(n):
		if i + 1 != tt[i]:
			r = i
	for i in range(l, r + 1):
		if i + 1 == tt[i]:
			xx += 1
	if xx == 0:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	siz = int(input())
	(ans, flag) = (0, False)
	ct = list(map(int, input().split()))
	for x in range(siz):
		if ct[x] != x + 1:
			if not flag:
				flag = True
				ans += 1
				if ans >= 2:
					break
		elif flag:
			flag = False
	print(min(ans, 2))


def b(a):
	sorted_a = sorted(a)
	while a[0] == sorted_a[0]:
		del a[0], sorted_a[0]
	while a[-1] == sorted_a[-1]:
		del a[-1], sorted_a[-1]
	for i in range(len(a)):
		if a[i] == sorted_a[i]:
			return True
	return False
for i in range(int(input())):
	_ = input()
	a = [int(i) for i in input().split()]
	if a == sorted(a):
		print(0)
	elif b(a):
		print(2)
	else:
		print(1)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, A):
	if A == sorted(A):
		return 0
	front = 0
	for (i, x) in enumerate(A):
		if x == i + 1:
			front += 1
		else:
			break
	back = 0
	for i in range(N - 1, -1, -1):
		if A[i] == i + 1:
			back += 1
		else:
			break
	ok = True
	for i in range(front, N - back):
		if A[i] == i + 1:
			ok = False
	if ok:
		return 1
	return 2
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N,) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	ans = solve(N, A)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if sorted(a) == a:
		print(0)
	else:
		output = 1
		count = 0
		for i in range(n):
			if a[i] != i + 1:
				if count == 2:
					output = 2
					break
				count = 1
			elif count == 1:
				count = 2
		print(output)


def solve(arr, l):
	if arr == sorted(arr):
		return 0
	head = True
	tail = False
	for i in range(l):
		if head == True and arr[i] != i + 1:
			head = False
		if head == False and arr[i] == i + 1:
			tail = True
		if tail == True and arr[i] != i + 1:
			return 2
	return 1
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	print(solve(a, n))


for I in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	fromleft = 0
	fromright = n - 1
	for i in range(n):
		if i + 1 != a[i]:
			break
	if i > 0:
		fromleft = i
	for i in range(n - 1, -1, -1):
		if i + 1 != a[i]:
			break
	if i > fromleft:
		fromright = i + 1
	displaced = 0
	positioned = 0
	for i in range(fromleft, fromright):
		if i + 1 == a[i]:
			positioned += 1
		else:
			displaced += 1
	if positioned == 0 and displaced == 0:
		print(0)
	elif positioned == 0 and displaced > 0:
		print(1)
	elif positioned > 0 and displaced > 0:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = [0] * n
	for i in range(n):
		if a[i] == i + 1:
			l[i] = 1
	count = 0
	for i in range(n):
		if l[i] == 1:
			count += 1
	if count == n:
		print('0')
	elif count == 0:
		print('1')
	else:
		count = 0
		fg = 0
		for i in range(n):
			if l[i] == 0 and fg == 0:
				fg = 1
			elif fg == 1 and l[i] == 1:
				fg = 2
			elif fg == 2 and l[i] == 0:
				fg = 3
				print('2')
				break
		if fg != 3:
			print('1')


for o in range(int(input())):
	n = int(input())
	a = map(int, input().split())
	pz = 0
	kz = n
	for i in enumerate(a):
		if i[0] + 1 != i[1]:
			if pz and kz <= i[0]:
				pz = -1
				break
			else:
				pz = i[0] + 1
				kz = n
		else:
			kz = i[1]
	if pz == 0:
		print(0)
	elif pz > 0:
		print(1)
	else:
		print(2)


import os
import sys
from io import BytesIO, IOBase

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		nums = list(map(int, input().split()))
		switch = 0
		curr = 'c' if 1 == nums[0] else 'w'
		i = 1
		while i < n:
			if nums[i] == i + 1 and curr == 'w':
				switch += 1
				curr = 'c'
			elif nums[i] != i + 1 and curr == 'c':
				switch += 1
				curr = 'w'
			i += 1
		if switch == 0:
			if curr == 'c':
				print(0)
			else:
				print(1)
		elif switch == 1:
			print(1)
		elif switch == 2 and curr == 'c':
			print(1)
		else:
			print(2)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	a = int(input())
	l = list(map(int, input().split()))
	cl = list(l)
	cl.sort()
	if l == cl:
		print(0)
	else:
		c = 0
		els = []
		for j in range(len(l)):
			if l[j] != j + 1:
				els.append(j + 1)
		nice = 1
		els.sort()
		for k in range(len(els) - 1):
			if els[k + 1] - els[k] > 1:
				nice = 0
		if nice == 1:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	parts = 0
	i = 0
	while True:
		while i < n and a[i] == i + 1:
			i += 1
		if i < n:
			parts += 1
			while i < n and a[i] != i + 1:
				i += 1
			if i == n:
				break
		else:
			break
	print(2 if parts > 2 else parts)


import os
import sys
from io import BytesIO, IOBase
profile = 0
pypy = 1

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))
import datetime

def main():
	T = iin()
	while T:
		T -= 1
		n = iin()
		a = lin()
		a2 = [0] * n
		for i in range(n):
			a2[i] = +(a[i] == i + 1)
		(l, r) = (0, n - 1)
		for i in range(n):
			if a2[i]:
				l += 1
			else:
				break
		for i in range(n - 1, -1, -1):
			if a2[i]:
				r -= 1
			else:
				break
		sol = 0
		if l < r:
			sol += 1
			ch = 1 if sum(a2[l:r + 1]) else 0
			sol += ch
		print(sol)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if pypy:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
if profile:
	import cProfile
	cProfile.run('main()')
else:
	main()


import math
LI = lambda : list(map(int, input().split()))
MI = lambda : map(int, input().split())
SI = lambda : input()
II = lambda : int(input())
t = II()
for q in range(t):
	n = II()
	a = LI()
	l = 0
	r = n - 1
	while l < n and a[l] == l + 1:
		l += 1
	while r > -1 and a[r] == r + 1:
		r -= 1
	if l == n:
		print(0)
	else:
		count = 0
		for i in range(l, r + 1):
			if a[i] == i + 1:
				count += 1
		if count == 0:
			print(1)
		else:
			print(2)


def main(n, lst):
	(ind0, ind1) = (-1, -1)
	for i in range(n):
		if lst[i] != i + 1:
			if ind0 == -1:
				ind0 = i
			if ind1 < i:
				ind1 = i
	lst = lst[ind0:ind1 + 1]
	if ind0 == -1:
		return 0
	else:
		for i in range(ind0, ind1 + 1):
			if i + 1 == lst[i - ind0]:
				return 2
		return 1
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	print(main(n, lst))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	sor = sorted(arr)
	ch = 0
	last = -2
	flag = 0
	for i in range(n):
		if arr[i] != sor[i]:
			if last != -2 and last != i - 1:
				flag = 1
			last = i
			ch += 1
	if ch == 0:
		print(0)
	elif ch == n or flag == 0:
		print(1)
	else:
		print(2)


import os
import sys
from io import BytesIO, IOBase
from itertools import groupby

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split(' ')))
		print('0' if sorted(a) == a else '1' if sum([1 if i + 1 != x else 0 for (i, x) in enumerate(a)]) == n or len(list(groupby(''.join(list(map(str, [1 if i + 1 != x else 0 for (i, x) in enumerate(a)])))))) <= 2 or (len(list(groupby(''.join(list(map(str, [1 if i + 1 != x else 0 for (i, x) in enumerate(a)])))))) == 3 and list(groupby(''.join(list(map(str, [1 if i + 1 != x else 0 for (i, x) in enumerate(a)])))))[0][0] == '0' and (list(groupby(''.join(list(map(str, [1 if i + 1 != x else 0 for (i, x) in enumerate(a)])))))[1][0] == '1') and (list(groupby(''.join(list(map(str, [1 if i + 1 != x else 0 for (i, x) in enumerate(a)])))))[2][0] == '0')) else '2')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	t = 0
	for i in range(n - 1, -1, -1):
		if l[i] == i + 1:
			continue
		else:
			t = i
			break
	if t == 0:
		print('0')
	else:
		j = []
		for i in range(t, -1, -1):
			if l[i] == i + 1:
				j.append(i + 1)
		a = False
		for i in range(len(j) - 1, -1, -1):
			if j[i] != len(j) - i:
				a = True
				break
		if a == False:
			print('1')
		else:
			print('2')


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	ans = i = 0
	c = 1
	d = n
	while i < n and c == lis[i]:
		c += 1
		i += 1
	i = n - 1
	while i >= 0 and d == lis[i]:
		d -= 1
		i -= 1
	for i in range(c - 1, d):
		if lis[i] == i + 1:
			ans += 1
	if c >= d:
		print(0)
	elif ans == 0:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	ai = list(map(int, input().split()))
	flag = 0
	flag2 = 0
	for i in range(0, n):
		if ai[i] != i + 1:
			flag = 1
		if ai[i] != i + 1 and flag2 == 1:
			print(2)
			break
		if ai[i] == i + 1 and flag == 1:
			flag2 = 1
	else:
		if flag == 1:
			print(1)
		else:
			print(0)


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7

def RLE(data):
	from itertools import groupby
	return [(x, len(list(grp))) for (x, grp) in groupby(data)]
for _ in range(INT()):
	N = INT()
	A = LIST()
	B = [0] * N
	for i in range(N):
		if A[i] == i + 1:
			B[i] = 1
	rle = RLE(B)
	cnt = 0
	for (x, ln) in rle:
		if x == 0:
			cnt += 1
	ans = min(cnt, 2)
	print(ans)


import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

def solve(lst):
	lst = [x - 1 for x in lst]
	if lst == list(range(len(lst))):
		return 0
	for (i, x) in enumerate(lst):
		if i != x:
			break
	for (j, x) in list(enumerate(lst))[::-1]:
		if j != x:
			break
	for (k, x) in enumerate(lst[i:j + 1], start=i):
		if k == x:
			return 2
	return 1

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
for case_num in range(int(input())):
	_ = int(input())
	lst = list(map(int, input().split()))
	res = solve(lst)
	print(res)


for _ in range(int(input())):
	n = int(input())
	arr = [0] + list(map(int, input().split()))
	cnt = 0
	inPos = True
	stage = 0
	ans = 1
	for i in range(1, n + 1):
		if i == arr[i]:
			if stage == 1:
				stage = 2
		else:
			inPos = False
			if stage == 0:
				stage = 1
			elif stage == 2:
				ans = 2
				break
	if inPos:
		print(0)
	else:
		print(ans)


rw = int(input())
for ewq in range(rw):
	n = int(input())
	a = list(map(int, input().split()))
	asorted = sorted(a)
	b = []
	s = 0
	t = True
	for i in range(n):
		if a[i] == i + 1:
			b.append(1)
		else:
			b.append(0)
	i = 0
	if b.count(1) == n:
		print(0)
		continue
	while i < n:
		if b[i] == 0:
			s += 1
			while i < n and b[i] == 0:
				i += 1
		i += 1
	t = False
	if s == 1:
		b0 = b.index(0)
		for i in range(b0, n):
			bk = i
			if b[i] == 1:
				break
		else:
			bk = n
		c = {i + 1 for i in range(b0, bk)}
		d = set()
		for i in range(b0, bk):
			d.add(a[i])
		t = False
		if c == d:
			t = True
	if t:
		print(1)
	else:
		print(2)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	fl = True
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			fl = False
	if fl:
		print(0)
	else:
		vis = [0] * n
		ma = [0] * n
		mi = [1000000] * n
		t = 1
		for i in range(n):
			if vis[i] != 0:
				continue
			if arr[i] == i + 1:
				continue
			cur = arr[i] - 1
			vis[i] = t
			ma[t] = max(ma[t], i)
			mi[t] = min(mi[t], i)
			while cur != i:
				vis[cur] = t
				ma[t] = max(ma[t], cur)
				mi[t] = min(mi[t], cur)
				cur = arr[cur] - 1
			t += 1
		flag = True
		cnt = 0
		for i in range(n):
			if vis[i] == 0:
				if cnt != 0:
					flag = False
			else:
				t = vis[i]
				if i == mi[t]:
					cnt += 1
				elif i == ma[t]:
					cnt -= 1
		if flag:
			print(1)
		else:
			print(2)


import sys
import math
import heapq
from collections import defaultdict, deque
from decimal import *

def r():
	return int(input())

def rm():
	return map(int, input().split())

def rl():
	return list(map(int, input().split()))
for _ in range(r()):
	n = r()
	a = rl()
	cnt = 0
	for i in range(n):
		if i + 1 == a[i]:
			cnt += 1
	prefix = 0
	suffix = 0
	i = 0
	while i < n:
		if i + 1 == a[i]:
			i += 1
			prefix += 1
		else:
			break
	i = n - 1
	while i >= 0:
		if i + 1 == a[i]:
			i -= 1
			suffix += 1
		else:
			break
	if prefix + suffix >= n:
		print(0)
	else:
		cnt -= prefix + suffix
		if cnt == 0:
			print(1)
		else:
			print(2)


for u in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	out = [[]]
	for i in range(n):
		if a[i] != i + 1:
			out[-1].append(i)
		else:
			out.append([])
	k = len(out) - out.count([])
	if k <= 1:
		print(k)
	else:
		print(2)


import math
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	flag = 1
	for i in range(n):
		if a[i] != i:
			flag = 0
	if flag:
		print('0')
		continue
	l = -1
	r = n
	for i in range(n):
		if a[i] != i:
			l = i
			break
	for i in range(n - 1, -1, -1):
		if a[i] != i:
			r = i
			break
	flag = 0
	for i in range(l, r + 1):
		if a[i] == i:
			flag = 1
	print(1 + flag)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for _ in range(testCases):
	n = int(input())
	arr = input_split()
	desired = [i + 1 for i in range(n)]
	wrong_inds = []
	for i in range(n):
		if desired[i] != arr[i]:
			wrong_inds.append(i)
	num_wrongs = len(wrong_inds)
	if num_wrongs == 0:
		ans = 0
	else:
		start = wrong_inds[0]
		consecutive = True
		for i in range(1, len(wrong_inds)):
			if start + i != wrong_inds[i]:
				consecutive = False
				break
		if consecutive:
			ans = 1
		else:
			ans = 2
	answers.append(ans)
print(*answers, sep='\n')


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	n = I()
	a = []
	for (i, j) in enumerate(R(), 1):
		if i != j:
			a += (i,)
	if a:
		m = max([a[i + 1] - a[i] for i in range(len(a) - 1)])
	if not a:
		print(0)
	elif m == 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	f = 0
	ans = 0
	if a == sorted(a):
		print(0)
	else:
		for i in range(n):
			if a[i] != i + 1:
				if f == 0:
					f = 1
				elif f == 2:
					f = 3
			elif f == 1:
				f = 2
		print(2 if f is 3 else 1)


for t in range(int(input())):
	n = int(input())
	arr = [int(k) for k in input().split()]
	ans = 0
	flag = 0
	for i in range(n):
		if arr[i] != i + 1 and flag == 0:
			flag = 1
			ans = 1
		if arr[i] == i + 1 and flag == 1:
			flag = 2
			ans = 1
		if arr[i] != i + 1 and flag == 2:
			ans = 2
			break
	print(ans)


for tc in range(int(input())):
	n = int(input())
	A = input().split(' ')
	wrong = []
	for i in range(n):
		A[i] = int(A[i])
		if A[i] != i + 1:
			wrong += [i + 1]
	if wrong == []:
		print(0)
	elif wrong[len(wrong) - 1] - wrong[0] == len(wrong) - 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	linear = [i for i in range(1, n + 1)]
	count = 0
	i = 0
	while i < n:
		j = i
		if arr[i] != linear[i]:
			count += 1
			while arr[j] != linear[j] and j < n - 1:
				j += 1
			i = j
		i += 1
	if count < 2:
		print(count)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	non_matching_indexes = list()
	for i in range(n):
		if i + 1 != a[i]:
			non_matching_indexes.append(i)
	matching_indexes_cnt = n - len(non_matching_indexes)
	if matching_indexes_cnt != n:
		if matching_indexes_cnt == 0:
			ans = 1
		elif len(non_matching_indexes) == 1 + (non_matching_indexes[-1] - non_matching_indexes[0]):
			ans = 1
		else:
			ans = 2
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ls = list(map(int, input().split()))
	unsortedSubArray = 0
	f = False
	for i in range(n):
		if ls[i] != i + 1:
			if not f:
				f = True
		elif f:
			unsortedSubArray += 1
			f = False
	if f:
		unsortedSubArray += 1
	print(min(2, unsortedSubArray))


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [(ch, len(list(g))) for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = N()
for i in range(t):
	n = N()
	a = RLL()
	if a == list(range(1, n + 1)):
		ans = 0
	else:
		b = [int(a[i] == i + 1) for i in range(n)]
		g = GP(b)
		if len(g) <= 2:
			ans = 1
		elif len(g) == 3:
			if g[0][0] == 1:
				ans = 1
			else:
				ans = 2
		else:
			ans = 2
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	if ar == sorted(ar):
		print(0)
	else:
		for i in range(n):
			if ar[i] != i + 1:
				break
		st = i
		for i in range(n - 1, -1, -1):
			if ar[i] != i + 1:
				break
		end = i
		ct = 0
		for i in range(st, end):
			if ar[i] == i + 1:
				ct += 1
		if ct == 0:
			print(1)
		else:
			print(2)


a = int(input())
for i in range(a):
	b = int(input())
	r1 = 0
	boo = False
	r2 = 0
	l = list(map(int, input().split()))
	for j in range(b):
		if not l[j] == j + 1:
			r1 = j
			boo = True
			break
	if boo == False:
		print(0)
	else:
		for j in range(b - 1, 0, -1):
			if not l[j] == j + 1:
				r2 = j
				break
		d = 0
		for j in range(r1, r2 + 1):
			if l[j] == j + 1:
				d += 1
				break
		if d == 0:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	t = []
	for i in range(n):
		if l[i] != i + 1:
			t.append(l[i])
	t.sort()
	if t != []:
		f = 0
		for i in range(len(t) - 1):
			if t[i + 1] - t[i] != 1:
				f = 1
				break
		if f:
			print(2)
		else:
			print(1)
	elif t == []:
		print(0)
	else:
		print(2)


import math

def main():
	n = int(input())
	lst = list(map(int, input().split()))
	all_true = True
	all_false = True
	for i in range(n):
		if lst[i] == i + 1:
			all_false = False
		else:
			all_true = False
	if all_false:
		print(1)
	elif all_true:
		print(0)
	else:
		cnt = 0
		prev = True
		if lst[0] != 1:
			cnt += 1
			prev = False
		for i in range(1, n):
			if lst[i] != i + 1:
				if prev:
					cnt += 1
					prev = False
			else:
				prev = True
		print(min(2, cnt))
t = int(input())
for i in range(t):
	main()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	else:
		e = 0
		b = []
		for i in range(n):
			if a[i] != i + 1:
				e = 1
				b.append(i)
		b.sort()
		c = min(b)
		for i in range(len(b)):
			b[i] -= c
		d = [i for i in range(len(b))]
		if d == b:
			e = 0
		if e == 1:
			print(2)
		else:
			print(1)


def solve(n, ls):
	k = 0
	e = True
	for i in range(n):
		ex = ls[i] == i + 1
		if e and (not ex):
			k += 1
			if k == 2:
				break
		e = ex
	return k

def main(istr, ostr):
	t = int(istr.readline())
	for _ in range(t):
		n = int(istr.readline())
		ls = list(map(int, istr.readline().split()))
		print(solve(n, ls), file=ostr)
import sys
main(sys.stdin, sys.stdout)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	from itertools import groupby
	t = int(input())
	ans_a = [''] * t
	for ti in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		g = [k for (k, v) in groupby([int(a[i] == i + 1) for i in range(n)])]
		if g == [1]:
			ans_a[ti] = '0'
		elif g.count(0) == 1:
			ans_a[ti] = '1'
		else:
			ans_a[ti] = '2'
	output(*ans_a)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	else:
		(flag, lrflag) = (False, False)
		(left, right) = (0, n + 1)
		if a[0] == 1 or a[n - 1] == n:
			lrflag = True
			for (l, num) in enumerate(a, 1):
				if l == num:
					left = l
				else:
					break
			for (r, i) in zip(reversed(a), reversed(range(1, n + 1))):
				if r == i:
					right = r
				else:
					break
		for (i, num) in enumerate(a, 1):
			if i == num and left < i < right:
				flag = True
		if lrflag == True and flag == False:
			print(1)
		elif lrflag == False and flag == False:
			print(1)
		else:
			print(2)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[i] == i + 1 for i in range(n)] + [1]
	f = -1
	sum = 0
	for i in range(n + 1):
		if b[i]:
			if i - f - 1 > 0:
				sum += 1
			f = i
	print(min(2, sum))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().strip().split()))[:n]
	if sorted(a) == a:
		print(0)
		continue
	flag = 0
	s = 0
	while s < n and a[s] == s + 1:
		s += 1
	e = n - 1
	while e - 1 > 0 and a[e] == e + 1:
		e -= 1
	for i in range(s, e + 1):
		if i + 1 == a[i]:
			flag = 1
			break
	if flag == 0:
		print(1)
	elif flag == 1:
		print(2)


cases = int(input())
answers = [] * 0
for problems in range(cases):
	n = int(input())
	a = [int(x) for x in input().split()]
	s = sorted(a)
	if s == a:
		answers.append(0)
	else:
		count = 0
		atBegin = True
		atEnd = False
		for i in range(len(a)):
			if a[i] == i + 1:
				if atBegin or atEnd:
					pass
				elif not atEnd:
					atEnd = True
				else:
					count += 1
			else:
				if atBegin:
					atBegin = False
				if atEnd:
					atEnd = False
					count += 1
		if count > 0:
			answers.append(2)
		else:
			answers.append(1)
for answer in answers:
	print(answer)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split() if i != '\n']
	change = [0] * n
	for i in range(n):
		if a[i] != i + 1:
			change[i] = 1
	ans = 0
	change.insert(0, 0)
	for i in range(len(change) - 1):
		if change[i + 1] == 1 and change[i] == 0:
			ans += 1
	sys.stdout.write(str(min(2, ans)) + '\n')


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
decimal.getcontext().prec = 46

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def modefiedSieve():
	mx = 10 ** 7 + 1
	sieve = [-1] * mx
	for i in range(2, mx):
		if sieve[i] == -1:
			sieve[i] = i
			for j in range(i * i, mx, i):
				if sieve[j] == -1:
					sieve[j] = i
	return sieve

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

def lcm(a, b):
	return a * b // math.gcd(a, b)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)

def list_input():
	return list(map(int, input().split()))

def num_input():
	return map(int, input().split())

def string_list():
	return list(input())

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, s, adj):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def maxSubArraySum(a, size):
	maxint = 10 ** 10
	max_so_far = -maxint - 1
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] >= arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def solve():
	n = int(input())
	arr = list_input()
	count = []
	first = last = False
	for i in range(n):
		if i + 1 == arr[i]:
			count.append(i + 1)
	if len(count) == n:
		print(0)
	elif len(count) == 0:
		print(1)
	else:
		c = 1
		while count != [] and count[0] == c:
			count.pop(0)
			c += 1
		c = n
		while count != [] and count[-1] == c:
			count.pop()
			c -= 1
		if count == []:
			print(1)
		else:
			print(2)
t = 1
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	a = -1
	b = n
	for i in range(n):
		if arr[i] != i + 1:
			break
		a = i
	for i in range(n - 1, -1, -1):
		if arr[i] != i + 1:
			break
		b = i
	if a == n - 1:
		print(0)
		continue
	ans = 1
	for i in range(a + 1, b):
		if arr[i] == i + 1:
			ans += 1
			break
	print(ans)


def solve(n, a):
	last = -1
	for i in range(n):
		if a[i] != i + 1:
			if last != -1 and last + 1 != i:
				return 2
			last = i
	return 0 if last == -1 else 1
tests = int(input())
for test in range(tests):
	n = int(input())
	a = list(map(int, input().split()))
	print(solve(n, a))


from sys import stdin, stdout

def INPUT():
	return list((int(i) for i in stdin.readline().split()))

def inp():
	return stdin.readline()

def out(x):
	return stdout.write(x)
import math
for _ in range(int(input())):
	n = int(input())
	A = INPUT()
	bool = [False] * n
	wrong = 0
	for i in range(n):
		if i + 1 == A[i]:
			bool[i] = True
		else:
			wrong += 1
	if wrong == 0:
		print(0)
	elif wrong == n:
		print(1)
	else:
		i = 0
		if bool[0] == True:
			while i < n and bool[i] is True:
				i += 1
			ind = i
			while i < n and bool[i] is False:
				i += 1
			x = ind - 1
			if i == n:
				ans = True
				x = ind - 1
				while ind < n:
					if A[ind] < A[x]:
						ans = False
					ind += 1
				if ans is False:
					print(2)
				else:
					print(1)
			else:
				new = i
				ind = x + 1
				while i < n and bool[i] is True:
					i += 1
				if i == n:
					ans = True
					while ind < new:
						if A[ind] < A[x] or A[ind] > A[new]:
							ans = False
						ind += 1
					if ans is False:
						print(2)
					else:
						print(1)
				else:
					print(2)
		else:
			i = 0
			while i < n and bool[i] is False:
				i += 1
			ind = i
			while i < n:
				if bool[i] == True:
					i += 1
					continue
				break
			if i == n:
				ans = True
				x = ind
				while ind >= 0:
					if A[ind] > A[x]:
						ans = False
					ind -= 1
				if ans is False:
					print(2)
				else:
					print(1)
			else:
				print(2)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	N = int(input())
	A = alele()
	B = sorted(A)
	if A == B:
		print(0)
	else:
		f = 0
		i = 0
		while i < N:
			if A[i] != B[i]:
				break
			i += 1
		j = N - 1
		while j >= 0:
			if A[j] != B[j]:
				break
			j -= 1
		ff = j - i
		while i <= j:
			if A[i] != B[i]:
				f += 1
			i += 1
		if f == ff + 1:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	if a == b:
		print('0')
		continue
	cnt = 0
	i = 0
	while a[i] == b[i]:
		i += 1
		if i == n:
			break
	ind1 = i
	i = n - 1
	while a[i] == b[i]:
		i -= 1
		if i == -1:
			break
	ind2 = i
	for i in range(ind1, ind2 + 1):
		if a[i] == b[i]:
			cnt += 1
	if cnt == 0:
		print('1')
	else:
		print('2')


I = lambda : list(map(int, input().split(' ')))

def check_0(lst):
	for i in range(len(lst)):
		if lst[i] != i + 1:
			return False
	return True

def check_1(lst):
	unb = []
	for i in range(len(lst)):
		if lst[i] != i + 1:
			unb.append(i)
	for i in range(len(unb) - 1):
		if unb[i + 1] - unb[i] != 1:
			return False
	return True

def main(lst):
	if check_0(lst):
		return 0
	if check_1(lst):
		return 1
	return 2
for _ in range(int(input())):
	n = int(input())
	lst = I()
	print(main(lst))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	count = 0
	f = 1
	for i in range(n):
		if arr[i] != i + 1:
			if f == 1:
				count += 1
				f = 0
		else:
			f = 1
	print(min(2, count))


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	f = 0
	flag = 0
	g = 0
	bigflag = 0
	for i in range(1, n + 1):
		if l[i - 1] != i:
			if flag == 0:
				f = 1
				g = 1
			else:
				bigflag = 1
				break
		elif g == 1:
			flag = 1
	if f == 0:
		print(0)
	elif bigflag == 0:
		print(1)
	else:
		print(2)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
from collections import Counter
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
tc = ii1()
for _ in range(tc):
	n = ii1()
	arr = iia()
	if sorted(arr) == arr:
		print(0)
	else:
		flag1 = flag2 = False
		count = 0
		for i in range(n):
			if arr[i] != i + 1 and flag2:
				count = 2
				break
			if arr[i] != i + 1 and (not flag1):
				flag1 = True
				count = 1
			elif arr[i] == i + 1 and flag1:
				flag2 = True
		print(count)


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	prev = True
	num = 0
	for j in range(n):
		if prev and a[j] != j + 1:
			num += 1
			prev = False
		elif a[j] == j + 1:
			prev = True
	if num > 2:
		print(2)
	else:
		print(num)


def f(a):
	n = len(a)
	for i in range(n):
		if a[i] == i + 1:
			continue
		for j in range(i, n):
			if a[j] != j + 1:
				continue
			for k in range(j, n):
				if a[k] == k + 1:
					continue
				return 2
			return 1
		return 1
	return 0
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	print(f(a))


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if sorted(a) == a:
		print(0)
	else:
		for i in range(n):
			if a[i] != i + 1:
				break
		f = 0
		for z in range(n - 1, i + 1, -1):
			if a[z] != z + 1:
				break
		for j in range(i, z):
			if a[j] == j + 1:
				f = 1
				break
		if f == 0:
			print(1)
		else:
			print(2)


from math import ceil
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(0)
		continue
	c = list(range(1, n + 1))
	check = [0] * n
	for i in range(n):
		if a[i] == c[i]:
			check[i] = 1
	f = 0
	for i in range(1, n):
		if check[i - 1] != check[i]:
			f += 1
	if f == 0 and check[0] == 1:
		print(0)
	elif f == 0 and check[0] == 0:
		print(1)
	elif f == 1:
		print(1)
	elif f == 2 and check[0] == 1:
		print(1)
	else:
		print(2)


from math import *
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		if a[i] != i + 1:
			k = i
			break
	else:
		print(ans)
		continue
	a.reverse()
	for i in range(n):
		if a[i] != n - i:
			m = n - i - 1
			break
	else:
		print(ans)
		continue
	a.reverse()
	c = 0
	for i in range(k, m + 1):
		if a[i] == i + 1:
			c = c + 1
	if c == 0:
		ans = 1
	else:
		ans = 2
	print(ans)


for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	champ = arr.copy()
	arr.sort()
	cnt = 0
	bool = False
	for i in range(n):
		if arr[i] != champ[i] and (not bool):
			cnt += 1
			bool = True
		elif arr[i] != champ[i] and bool:
			continue
		elif arr[i] == champ[i]:
			bool = False
	if cnt == 0:
		print(0)
	elif cnt == 1:
		print(1)
	else:
		print(2)


from sys import stdin
for _ in range(int(stdin.readline())):
	length = int(stdin.readline())
	array = list(map(int, stdin.readline().split()))
	count = 0
	start = length
	end = 0
	for i in range(length):
		if array[i] != i + 1:
			start = i
			break
	for i in range(length - 1, -1, -1):
		if array[i] != i + 1:
			end = i
			break
	if start > end:
		print(0)
	else:
		for i in range(start, end + 1):
			if array[i] == i + 1:
				count += 1
		if count == 0:
			print(1)
		elif count == end - start + 1:
			print(0)
		else:
			print(2)


t = int(input())
while t:
	t = t - 1
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	flag = 0
	for i in range(1, n + 1):
		if a[i - 1] == i:
			flag = 0
		elif flag == 0:
			cnt += 1
			flag = 1
	print(min(2, cnt))


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	chcounter = 0
	if arr[0] == 1:
		falseflag = False
		trueflag = True
	else:
		falseflag = True
		trueflag = False
	for j in range(n):
		if arr[j] == j + 1:
			if falseflag:
				falseflag = False
				trueflag = True
				chcounter += 1
				if chcounter > 2:
					break
		elif trueflag:
			trueflag = False
			falseflag = True
			chcounter += 1
			if chcounter > 2:
				break
	if chcounter == 0:
		if trueflag == True:
			print(0)
		else:
			print(1)
	elif chcounter == 1:
		print(1)
	elif chcounter == 2:
		if arr[0] == 1 and arr[-1] == n:
			print(1)
		else:
			print(2)
	elif chcounter > 2:
		print(2)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	left = -1
	right = n
	for i in range(n):
		if a[i] != i + 1:
			left = i
			break
	for i in range(n - 1, -1, -1):
		if a[i] != i + 1:
			right = i + 1
			break
	if left == -1:
		print(0)
	else:
		cnt = 0
		for i in range(left, right):
			if a[i] == i + 1:
				cnt += 1
		if cnt == 0:
			print(1)
		else:
			print(2)


for t in range(int(input())):
	n = int(input())
	data = [int(x) for x in input().split()]
	count = 0
	os = 0
	d = False
	for i in range(n):
		if data[i] == i + 1:
			count += 1
			d = False
		elif not d:
			d = True
			os += 1
	if count == n:
		print(0)
	elif count != 0 and os != 1:
		print(2)
	else:
		print(1)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	if a == b:
		print(0)
		continue
	ans = 0
	if a[0] != 1:
		ans = 1
	for i in range(1, n):
		if a[i] != i + 1 and a[i - 1] == i:
			ans += 1
	if ans == 1:
		print(ans)
	else:
		print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		if a[i] == i + 1:
			a[i] = 0
		else:
			a[i] = 1
	first = None
	last = None
	for i in range(n):
		if a[i]:
			if first == None:
				first = i
			last = i
	if first == None and last == None:
		print(0)
	else:
		count = 0
		for i in range(first, last + 1):
			if a[i] == 0:
				count += 1
		if count == 0:
			print(1)
		else:
			print(2)


import sys
import os
readline = sys.stdin.readline
t = int(input())
while t:
	n = int(input())
	t -= 1
	a = list(map(int, input().split()))
	l = 0
	r = n - 1
	while l < n and a[l] == l + 1:
		l += 1
	while r > 0 and a[r] == r + 1:
		r -= 1
	if l > r:
		print(0)
		continue
	res = 0
	for i in range(l, r + 1):
		if a[i] == i + 1:
			res = 1
			break
	print(res + 1)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = ''
	for i in range(n):
		if a[i] == i + 1:
			s += ' '
		else:
			s += '1'
	l = s.split()
	print(min(2, len(l)))


from sys import stdin

def iinput():
	return int(stdin.readline())

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
t = iinput()
while t:
	t -= 1
	n = iinput()
	a = linput()
	b = sorted(a)
	l = 0
	r = n - 1
	while l < n and a[l] == b[l]:
		l += 1
	while r > -1 and a[r] == b[r]:
		r -= 1
	if l == n:
		print(0)
	else:
		(x, y) = (r, l)
		for i in range(l, r + 1):
			if a[i] == b[i]:
				x = min(x, i)
				y = max(y, i)
		if x <= y:
			print(2)
		else:
			print(1)


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	n = II()
	a = LI() + [n + 1]
	(ans, p) = (0, 0)
	for (c, v) in enumerate(a, 1):
		if c == v:
			if c - p > 1:
				ans += 1
			p = c
	print(min(2, ans))


try:
	for _ in range(int(input())):
		n = int(input())
		arr = [int(i) for i in input().split()]
		tem = [i for i in range(n) if arr[i] != i + 1]
		if len(tem) == 0:
			print(0)
		elif tem[-1] - tem[0] + 1 == len(tem):
			print(1)
		else:
			print(2)
except:
	pass


t = 1
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	(ans, flag) = (0, 1)
	for (i, el) in enumerate(a):
		if el == i + 1:
			flag = 1
		elif flag:
			ans += 1
			flag = 0
	print(min(ans, 2))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	inc = 0
	for i in range(n):
		if i + 1 == a[i]:
			inc += 1
	if inc == 0:
		print(1)
	elif inc == n:
		print(0)
	else:
		start = 0
		end = 0
		for i in range(n):
			if i + 1 == a[i]:
				start += 1
			else:
				break
		for i in reversed(range(n)):
			if i + 1 == a[i]:
				end += 1
			else:
				break
		if start + end == inc:
			print(1)
		else:
			print(2)


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	arr = [0] * n
	for i in range(n):
		if lis[i] == i + 1:
			arr[i] = 1
	s = ''.join(map(str, arr))
	if '0' not in s:
		print(0)
		continue
	res = s.split('1')
	cou = 0
	for i in res:
		if len(i) > 0:
			cou += 1
	if cou > 1:
		print(2)
	else:
		print(1)


def specialSorting(n, ar):
	sorted_ar = sorted(ar)
	ans = 0
	same_posi = False
	if ar == sorted_ar:
		return print(0)
	for i in range(n):
		if ar[i] == i + 1 and ar[:i + 1] != sorted_ar[:i + 1] and (ar[i:] != sorted_ar[i:]):
			same_posi = True
	if same_posi == False:
		return print(1)
	return print(2)
t = int(input())
for i in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	specialSorting(n, ar)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n
avl = AvlTree()

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	t = [] + l
	t.sort()
	r = 0
	er = 0
	te = 0
	for i in range(n):
		if t[i] != l[i]:
			te = 1
		if te == 1 and t[i] == l[i]:
			r = 1
		if r == 1 and t[i] != l[i]:
			er = 1
	if te == 0:
		print(0)
	else:
		print(er + 1)


def fast(arr):
	lastBadIndex = None
	for (i, num) in enumerate(arr):
		j = i + 1
		if j != num:
			if lastBadIndex in [None, j - 1]:
				lastBadIndex = j
			else:
				return 2
	if lastBadIndex is None:
		return 0
	else:
		return 1

def test():
	arr = [9, 1, 8, 7, 6, 2, 5, 3, 4]
	f = fast(arr)
	print(f)

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = [int(x) for x in input().split()]
		result = fast(arr)
		print(result)
main()


import io, os
R = lambda : map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	a = list(R())
	(pre, last) = (0, n - 1)
	while pre < n and a[pre] == pre + 1:
		pre += 1
	while last >= 0 and a[last] == last + 1:
		last -= 1
	if pre >= last:
		print('0')
	else:
		t = []
		for i in range(pre, last + 1):
			if a[i] != i + 1:
				a[i] = i + 1
			else:
				t.append(a[i])
		if len(t):
			print('2')
		else:
			print('1')


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s)
	sys.stdout.write('\n')

def wi(n):
	sys.stdout.write(str(n))
	sys.stdout.write('\n')

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')

def s1(n, a):
	cnt = 0
	c1 = set()
	c2 = set()
	bad = 0
	for i in range(n):
		if a[i] == i + 1:
			if c1 == c2:
				if len(c1) > 0:
					cnt += 1 + bad
					bad = 0
					c1 = set()
					c2 = set()
			else:
				bad = 1
		else:
			c1.add(i + 1)
			c2.add(a[i])
	if len(c1) > 0:
		cnt += 1 + bad
	return cnt

def solve(n, a):
	cnt = 0
	c = 0
	for i in range(n):
		if a[i] == i + 1:
			if c > 0:
				cnt += 1
				c = 0
		else:
			c += 1
	if c > 0:
		cnt += 1
	return min(cnt, 2)

def main():
	for _ in range(ri()):
		n = ri()
		a = ria()
		wi(solve(n, a))
main()


t = int(input())
while t:
	t -= 1
	n = int(input())
	tarr = [int(x) for x in input().split()]
	if tarr == sorted(tarr):
		print(0)
		continue
	arr = [[i + 1, e] for (i, e) in enumerate(tarr)]
	left = 0
	right = n - 1
	while left < n:
		if arr[left][0] == arr[left][1]:
			left += 1
		else:
			break
	while right >= 0:
		if arr[right][0] == arr[right][1]:
			right -= 1
		else:
			break
	c = 0
	for i in range(left, right + 1):
		if arr[i][0] == arr[i][1]:
			c += 1
			break
	if c > 0:
		print(2)
	else:
		print(1)


t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	l = -1
	r = -1
	for j in range(n):
		if lst[j] != j + 1:
			l = j
			break
	for j in range(n - 1, -1, -1):
		if lst[j] != j + 1:
			r = j
			break
	if l == -1 and r == -1:
		print(0)
	else:
		c = 0
		for h in range(l, r + 1):
			if lst[h] == h + 1:
				c += 1
				break
		if c == 0:
			print(1)
		else:
			print(2)


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fli():
	return [float(x) for x in input().split()]

def gi():
	return [x for x in input().split()]

def fi():
	return int(input())

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
t = fi()
while t > 0:
	t -= 1
	n = fi()
	a = li()
	if a == sorted(a):
		print(0)
	else:
		b = sorted(a)
		flag = 0
		d = {}
		for i in range(len(b)):
			if b[i] == a[i]:
				flag += 1
			elif flag in d:
				d[flag] += 1
			else:
				d[flag] = 1
		print(2 if len(d) > 1 else 1)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	else:
		(f, l) = (-1, -1)
		for i in range(n):
			if a[i] != i + 1:
				if f == -1:
					f = i + 1
				else:
					l = i + 1
		fl = 0
		for i in range(f - 1, l):
			if a[i] == i + 1:
				fl = 1
				break
		if fl:
			print(2)
		else:
			print(1)


t = int(input())
while t > 0:
	n = int(input())
	a = [int(ele) for ele in input().split()]
	i = n
	while 1 and i > 0:
		if a[-1] == i:
			del a[-1]
			i -= 1
		else:
			break
	l = len(a)
	count = 0
	i = 1
	while 1 and i < l:
		if a[0] == i:
			del a[0]
			l -= 1
			i += 1
			count += 1
		else:
			break
	if len(a) == 0:
		print(0)
	else:
		notIn = 0
		l = len(a)
		for i in range(l):
			if count + i + 1 != a[i]:
				notIn += 1
		if notIn == l:
			print(1)
		else:
			print(2)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
import threading
from math import gcd

def lcm(a, b):
	return a * b // gcd(a, b)

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = list(map(int, input().split()))
		arr.insert(0, 0)
		a = list(range(0, n + 1))
		start = 0
		end = n
		b = False
		while start < n and arr[start] == start:
			start += 1
		while end > start and arr[end] == end:
			end -= 1
		for i in range(start, end + 1):
			if arr[i] == i:
				b = True
		if arr == a:
			print(0)
		elif b:
			print(2)
		else:
			print(1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def MI():
	return map(int, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RA():
	return map(int, open(0).read().split())

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in R(V)]
	FromStdin = True if ls == None else False
	for i in R(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in R(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in R(base ** n):
		s = [tb // base ** bt % base for bt in R(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print(['No', 'Yes'][x])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()
show_flg = False
show_flg = True
ans = 0
for i in rep(I()):
	ans = -1
	n = I()
	a = LI_()
	b = list(rep(n))
	if a == b:
		ans = 0
	else:
		ans = 1
		(l, r) = (-1, n)
		for i in range(n):
			if a[i] == b[i]:
				l = i
			else:
				break
		for i in range(n)[::-1]:
			if a[i] == b[i]:
				r = i
			else:
				break
		for i in range(l + 1, r - 1):
			if a[i] == b[i]:
				ans = 2
	print(ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass
T = int(input())
for _ in range(T):
	n = L()[0]
	A = L()
	x = sorted(A)
	if A == x:
		print(0)
	else:
		B = [str(int(A[i] == i + 1)) for i in range(n)]
		x = ''.join(B)
		s = x.split('1')
		count = 0
		for ele in s:
			if ele:
				count += 1
		print(min(count, 2))


for _ in range(int(input())):
	N = int(input())
	A = list(map(int, input().split()))
	B = A.copy()
	B.sort()
	if A == B:
		print(0)
	else:
		index = []
		for i in range(N):
			if A[i] != i + 1:
				index.append(i + 1)
		temp = 0
		for i in range(1, len(index)):
			t = index[i] - index[i - 1]
			if t != 1:
				temp = 1
				break
		if temp == 1:
			print(2)
		else:
			print(1)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if arr == sorted(arr):
		print(0)
	else:
		i = 0
		ans = 0
		while i + 1 == arr[i]:
			i += 1
		while i < n:
			if i + 1 == arr[i]:
				if arr[i - 1] != i:
					if i != n - 1:
						ans += 1
				elif i == n - 1:
					ans -= 1
			i += 1
		if ans:
			print(2)
		else:
			print(1)


t = int(input())
i = 0
while i < t:
	n = int(input())
	a = [int(g) for g in input().split()]
	b = sorted(a)
	if b == a:
		print(0)
		i += 1
		continue
	if b == a[::-1]:
		print(1)
		i += 1
		continue
	j = 0
	same = 0
	la = len(a)
	while j < la:
		if int(a[j]) == j + 1:
			same += 1
		else:
			break
		j += 1
	k = 1
	back_same = 0
	while k < la:
		if int(a[la - k]) == la - k + 1:
			back_same += 1
		else:
			break
		k += 1
	arr_to_check = list(a[same:len(a) - back_same])
	x = sorted(arr_to_check)
	l = 0
	same_place = True
	while l < len(x):
		if int(arr_to_check[l]) == int(x[l]):
			same_place = True
			break
		else:
			same_place = False
		l += 1
	if same_place:
		print(2)
	else:
		print(1)
	i += 1


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	a = l()
	(first, last) = (-1, -1)
	for i in range(n):
		if a[i] != i + 1:
			first = i
			break
	for j in range(n - 1, -1, -1):
		if a[j] != j + 1:
			last = j
			break
	if last == first == -1:
		out('0\n')
		continue
	cnt = 0
	for i in range(first + 1, last):
		if a[i] == i + 1:
			cnt += 1
	if cnt:
		out('2\n')
		continue
	out('1\n')


import sys
q = int(input())
for i in range(q):
	n = int(input())
	a = [int(j) for j in sys.stdin.readline().split()]
	if a[0] == 1:
		status = 1
		start = 1
	else:
		status = 0
		start = 0
	swap = 0
	for i in range(n):
		if i + 1 == a[i] and status == 0:
			swap += 1
			status = 1
		elif i + 1 != a[i] and status == 1:
			swap += 1
			status = 0
	if start == 1 and swap == 0:
		print(0)
	elif swap <= 1 and start == 0 or (swap <= 2 and start == 1):
		print(1)
	else:
		print(2)


t = int(input().split()[0])
for case in range(t):
	n = int(input().split()[0])
	arr = list(map(int, input().split()))
	(start, end) = (0, n - 1)
	for i in range(n):
		if arr[i] == i + 1:
			start += 1
		else:
			break
	for i in range(n - 1, -1, -1):
		if arr[i] == i + 1:
			end -= 1
		else:
			break
	ans = 1
	if start == n:
		ans = 0
	for i in range(start, end + 1):
		if arr[i] == i + 1:
			ans = 2
			break
	print(ans)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	for i in range(n):
		if l[i] - 1 != i:
			c += 1
	if c == n:
		print(1)
	elif c == 0:
		print(0)
	else:
		(f1, f2) = (0, 0)
		arr = []
		for i in range(n):
			if l[i] - 1 != i:
				arr.append(i)
		for i in range(1, len(arr)):
			if arr[i] - arr[i - 1] > 1:
				f1 = 1
				break
		if f1 == 1:
			print(2)
		else:
			print(1)


import sys
sys.setrecursionlimit(10 ** 5)

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]
for _ in range(II()):
	n = II()
	arr = [0] + LI()
	ans = 0
	for i in range(n):
		if arr[i] == i and arr[i + 1] != i + 1:
			ans += 1
	print(min(2, ans))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == list(range(1, n + 1)):
		ans = 0
	else:
		i = 0
		while a[i] == i + 1:
			i += 1
		while a[-1] == len(a):
			a.pop()
		ans = 1
		for j in range(i, len(a)):
			if a[j] == j + 1:
				ans = 2
				break
	print(ans)


t = int(input())
for j in range(t):
	k = s = 0
	n = int(input())
	y = n + 1
	L = map(int, input().split())
	L = list(L)
	for i in range(n):
		if L[i] != i + 1:
			k = k + 1
		elif k > 0:
			y = i
			break
	if k == 0:
		print(0)
	else:
		for i in range(y + 1, n):
			if L[i] != i + 1:
				s = s + 1
				break
	if k > 1 and s == 0:
		print(1)
	elif s > 0:
		print(2)


t = int(input())
while t:
	t -= 1
	n = int(input())
	l = [int(x) for x in input().split()]
	cnt = 0
	end = -1
	start = -1
	nstart = -1
	nend = -1
	for i in range(len(l)):
		if i + 1 == l[i]:
			if start == -1:
				start = i
			cnt += 1
			end = i
		else:
			if nstart == -1:
				nstart = i
			nend = i
	if cnt == n:
		print('0')
	elif cnt == 0:
		print('1')
	elif cnt == end - start + 1 and (start == 0 or end == n - 1):
		print('1')
	elif nend - nstart + 1 == n - cnt:
		print('1')
	else:
		print('2')


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = a
	if sorted(b) == a:
		print(0)
		continue
	c = 0
	i = 0
	j = n - 1
	while a[i] == i + 1:
		i += 1
	while a[j] == j + 1:
		j -= 1
	for k in range(i, j + 1):
		if a[k] != k + 1:
			c += 1
	if c == j - i + 1:
		print(1)
	else:
		print(2)


from sys import stdin, stdout
test = int(stdin.readline())
for _ in range(test):
	N = int(stdin.readline())
	a = [int(x) for x in stdin.readline().split()]
	b = sorted(a)
	if a == b:
		print(0)
		continue
	temp = [int(a[i] == b[i]) for i in range(N)]
	if len(set(temp)) == 1:
		print(1)
		continue
	one = True
	found0 = False
	found1 = False
	for i in range(N):
		if found1:
			if temp[i] == 0:
				one = False
				break
			continue
		if found0:
			if temp[i] == 1:
				found1 = True
				continue
			continue
		if temp[i] == 0:
			found0 = True
	print(1) if one else print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	if l == sorted(l):
		print(0)
	else:
		kusoks = 0
		(start, end) = (-1, -1)
		for (i, v) in enumerate(l):
			if i + 1 == v:
				if i != 0:
					if start != -1:
						end = i
					else:
						start = i
						end = i
			elif start != -1:
				kusoks += 1
				start = -1
				end = -1
		if kusoks == 0:
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	t1 = 0
	b1 = []
	b2 = []
	f1 = 0
	f2 = 0
	f3 = 0
	for i in range(n):
		if a[i] != i + 1:
			t1 += 1
			f1 = 1
			if f2 == 1:
				f3 = 1
				break
		elif f1 == 1:
			f2 = 1
	if t1 == 0:
		print(0)
	elif t1 == n:
		print(1)
	elif f3 == 1:
		print(2)
	else:
		print(1)


for T in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arn = sorted(arr)
	count = 0
	t = 0
	for i in range(len(arr)):
		if arr[i] != arn[i]:
			count += 1
		elif arr[i] == arn[i] and count != 0:
			count = 0
			t += 1
	if count != 0:
		t += 1
	print(min(t, 2))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	matches = []
	for i in range(n):
		if arr[i] == i + 1:
			matches.append(i + 1)
	if len(matches) == n:
		print(0)
	else:
		z = list(set(range(1, n + 1)) - set(matches))
		z.sort()
		if z == list(range(z[0], z[-1] + 1)):
			print(1)
		else:
			print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	(a, b) = (0, 0)
	st = []
	j = 1
	for i in ar:
		if i == j:
			a += 1
			st += ['1']
		else:
			b += 1
			st += ['0']
		j += 1
	if b == 0:
		print(0)
	elif a == 0:
		print(1)
	else:
		st = ''.join(st)
		if b * '0' in st:
			print(1)
		else:
			print(2)


for ii in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	j1 = 0
	j2 = n - 1
	c = 0
	if b == a:
		print(0)
	else:
		if a[0] == b[0]:
			c = 0
			for i in range(1, n):
				if a[i] != b[i]:
					j1 = i
					break
		if a[n - 1] == b[n - 1]:
			for i in range(n - 1, 0, -1):
				if a[i] != b[i]:
					j2 = i
					break
		for i in range(j1, j2 + 1):
			if a[i] == b[i]:
				c += 1
				break
		if c == 0:
			print(1)
		else:
			print(2)


ans = ''
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	i = 0
	j = n - 1
	flag1 = True
	flag2 = True
	falg3 = 0
	while flag1 or flag2:
		if i >= j:
			falg3 = 1
			break
		if arr[i] != i + 1:
			flag1 = False
		else:
			i += 1
		if arr[j] != j + 1:
			flag2 = False
		else:
			j -= 1
	if falg3:
		ans += '0\n'
	else:
		cnt = 0
		while i <= j:
			if arr[i] == i + 1:
				cnt += 1
			i += 1
		if cnt:
			ans += '2\n'
		else:
			ans += '1\n'
print(ans)


T = int(input())

def solve():
	N = int(input())
	a = [int(x) for x in input().split()]
	fst_wrong = None
	for i in range(N):
		if a[i] != i + 1:
			fst_wrong = i
			break
	last_wrong = None
	for i in range(N - 1, -1, -1):
		if a[i] != i + 1:
			last_wrong = i
			break
	if fst_wrong is None:
		assert last_wrong is None
		return 0
	has_fixpoint = False
	for i in range(fst_wrong, last_wrong + 1):
		if a[i] == i + 1:
			has_fixpoint = True
	if not has_fixpoint:
		return 1
	return 2
for _ in range(T):
	print(solve())


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	left = 0
	right = n
	for j in range(n):
		if a[j] == j + 1:
			left += 1
		else:
			break
	for j in range(1, n - left + 1):
		if a[-j] == n - j + 1:
			right -= 1
		else:
			break
	if left == n:
		print(0)
	else:
		for j in range(left, right):
			if a[j] == j + 1:
				print(2)
				break
		else:
			print(1)


from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	temp = 0
	for i in range(n):
		if ar[i] != i + 1:
			temp += 1
	if sorted(ar) == ar:
		print(0)
	elif temp == n:
		print(1)
	else:
		x = 0
		for i in range(n):
			if ar[i] != i + 1:
				x = i
				break
		y = n - 1
		for i in range(n - 1, -1, -1):
			if ar[i] != i + 1:
				y = i + 1
				break
		ans = 0
		for i in range(x, y):
			if ar[i] == i + 1:
				ans += 1
		if ans == 0:
			print(1)
		else:
			print(2)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(item) for item in input().split()]
	diff = 0
	same = 0
	prev = 1
	block = 0
	for (i, item) in enumerate(a):
		if i + 1 == item:
			same += 1
			prev = 1
		else:
			diff += 1
			if prev == 1:
				prev = 0
				block += 1
	if same == n:
		print(0)
	elif block == 1:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if arr == [i + 1 for i in range(n)]:
		print(0)
		continue
	cnt = 0
	was_cur = False
	for i in range(n):
		if i != 0:
			if arr[i - 1] != i:
				was_cur = True
			else:
				was_cur = False
		if not was_cur and arr[i] != i + 1:
			cnt += 1
	if n == 2:
		print(1)
	elif n == 3:
		print(cnt)
	else:
		print(min(cnt, 2))


from __future__ import division, print_function
import os, sys
import math
import collections
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

class my_dictionary(dict):

	def __init__(self):
		self = dict()

	def add(self, key, value):
		self[key] = value

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(100000000)
	threading.stack_size(40960000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r))

def binary_search(arr, low, high, x):
	if high >= low:
		mid = (high + low) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return binary_search(arr, low, mid - 1, x)
		else:
			return binary_search(arr, mid + 1, high, x)
	else:
		return -1

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def padded_bin_with_complement(x):
	if x < 0:
		return bin(2 ** 16 - abs(x))[2:].zfill(16)
	else:
		return bin(x)[2:].zfill(16)

def binaryToDecimal(binary):
	binary1 = binary
	(decimal, i, n) = (0, 0, 0)
	while binary != 0:
		dec = binary % 10
		decimal = decimal + dec * pow(2, i)
		binary = binary // 10
		i += 1
	print(decimal)

def CountFrequency(my_list):
	freq = {}
	for item in my_list:
		if item in freq:
			freq[item] += 1
		else:
			freq[item] = 1
	return freq

def pos(a):
	b = [0] * len(a)
	c = sorted(a)
	for i in range(len(a)):
		for j in range(len(a)):
			if c[j] == a[i]:
				b[i] = j
				break
	return b

def smallestDivisor(n):
	if n % 2 == 0:
		return 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			return i
		i += 2
	return n

def commonn(a, b, n):
	c = []
	for i in range(n):
		if a[i] == b[i]:
			c.append('-1')
		else:
			c.append(b[i])
	return c

def primeFactors(n):
	j = []
	while n % 2 == 0:
		j.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			j.append(int(n))
			n = n / i
	if n > 2:
		j.append(int(n))
	return j

def sumdigit(n):
	n = str(n)
	k = 0
	for i in range(len(n)):
		k += int(n[i])
	return k

def main():
	for _ in range(ii()):
		n = ii()
		a = li()
		b = []
		first = 0
		last = 0
		f = 0
		for i in range(n):
			if a[i] != i + 1:
				break
			else:
				first += 1
		for i in range(n):
			if a[n - i - 1] != n - i:
				break
			else:
				last += 1
		for i in range(first, n - last):
			if a[i] == i + 1:
				f = 1
			b.append(i + 1)
		if f:
			print(2)
		elif a == sorted(a):
			print(0)
		else:
			print(1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from math import *
from collections import *
from operator import itemgetter
import bisect
from heapq import *
i = lambda : input()
ii = lambda : int(input())
iia = lambda : list(map(int, input().split()))
isa = lambda : list(input().split())
I = lambda : list(map(int, input().split()))
chrIdx = lambda x: ord(x) - 96
idxChr = lambda x: chr(96 + x)
t = ii()
for _ in range(t):
	n = ii()
	a = iia()
	b = [i + 1 for i in range(n)]
	c = []
	for i in range(n):
		c.append(a[i] - (i + 1))
	cnt = 0
	nz = 0
	nnz = 0
	ans = 0
	j = 0
	while j < n:
		i = j
		nz = 0
		nnz = 0
		cz = 0
		while i < n:
			cnt += c[i]
			if c[i] == 0:
				nz += 1
				k = i + 1
				while k < n:
					if c[k] == 0:
						k += 1
					else:
						break
				i = k - 1
			else:
				nnz += 1
			if cnt == 0:
				break
			i += 1
		if nnz > 0:
			ans += nz + 1
		j = i + 1
	print(min(ans, 2))


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	s = sorted(A)
	if A == s:
		print(0)
		continue
	ok = True
	(st, end) = (0, n - 1)
	for i in range(n):
		if A[i] == s[i]:
			st = i
		else:
			break
	for i in range(n - 1, -1, -1):
		if A[i] == s[i]:
			end = i
		else:
			break
	for i in range(st + 1, end):
		if A[i] == s[i]:
			ok = False
	if ok:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	t1 = 0
	t2 = n
	for i in range(n):
		if l[i] != i + 1:
			t1 = i
			break
	for i in range(n - 1, -1, -1):
		if l[i] != i + 1:
			t2 = i
			break
	for i in range(t1, t2):
		if l[i] == i + 1:
			c += 1
	if c == 0:
		print(1)
	elif c == n:
		print(0)
	else:
		print(2)


t = int(input())

def number_of_continous_disorder(l):
	sort_l = sorted(l)
	count = 0
	previous_in_disorder = False
	for i in range(len(l)):
		if l[i] == sort_l[i]:
			previous_in_disorder = False
		elif not previous_in_disorder:
			count += 1
			previous_in_disorder = True
	return count

def solve():
	n = int(input())
	l = list(map(int, input().split()))
	count = number_of_continous_disorder(l)
	if count == 0:
		print(0)
	elif count == 1:
		print(1)
	else:
		print(2)
	return
while t:
	solve()
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	f = 1
	g = 1
	for i in range(n):
		if i + 1 == a[i]:
			cnt += 1
		elif f:
			f = 0
		elif i > 0 and a[i - 1] == i:
			g = 0
	if cnt == n:
		print(0)
	elif g:
		print(1)
	else:
		print(2)


for i in range(int(input())):
	n = int(input())
	arr = [int(c) for c in input().split()]
	s = list(range(1, n + 1))
	s.sort()
	if arr == s:
		print(0)
	else:
		a = []
		for i in range(n):
			if arr[i] == i + 1:
				if len(a) == 0:
					a.append(True)
				elif a[-1] == False:
					a.append(True)
			elif len(a) == 0:
				a.append(False)
			elif a[-1] == True:
				a.append(False)
		if a == [True, False] or a == [False, True] or a == [True, False, True]:
			print(1)
			continue
		if a == [False]:
			print(1)
		else:
			print(2)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)

def solution(a, n):
	if a == sorted(a):
		return 0
	one = True
	for i in range(n):
		if a[i] == i + 1:
			one = False
			break
	if one:
		return 1
	i = 0
	while i < n and a[i] == i + 1:
		i += 1
	while i < n and a[i] != i + 1:
		i += 1
	while i < n and a[i] == i + 1:
		i += 1
	if i == n:
		return 1
	return 2

def main():
	T = 1
	T = ri()
	for i in range(T):
		n = ri()
		a = ria()
		x = solution(a, n)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())
for case in range(itg()):
	n = itg()
	arr = list(mpint())
	check = [arr[i] == 1 + i for i in range(n)]
	try:
		left_false = check.index(False)
	except ValueError:
		print(0)
		continue
	have_true = False
	for i in range(left_false + 1, n):
		if have_true and (not check[i]):
			print(2)
			break
		have_true = check[i]
	else:
		print(1)


t = int(input())
for tc in range(t):
	n = int(input())
	line = input().split()
	a1 = []
	a2 = []
	ans = -1
	for i in range(n):
		a1.append(int(line[i]))
		if a1[i] != i + 1:
			a2.append(i + 1)
	if len(a2) == 0:
		ans = 0
	else:
		a2.sort()
		for i in range(1, len(a2)):
			if a2[i - 1] + 1 != a2[i]:
				ans = 2
	if ans == -1:
		print('1')
	else:
		print(ans)


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	if A == sorted(A):
		print(0)
	else:
		if A[0] == 1:
			tr = True
		else:
			tr = False
		x = 0
		if not tr:
			x += 1
		for i in range(len(A)):
			if A[i] == i + 1:
				if tr != True:
					tr = True
			elif tr == True:
				x += 1
				tr = False
		if x == 1:
			print(1)
		else:
			print(2)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI_()
		l = 0
		r = n - 1
		while l < n and a[l] == l:
			l += 1
		while r > 0 and a[r] == r:
			r -= 1
		c = 0
		for i in range(l, r + 1):
			if a[i] == i:
				c += 1
		if l >= r:
			r = 0
		elif c == 0:
			r = 1
		else:
			r = 2
		rr.append(r)
	return JA(rr, '\n')
print(main())


t = int(input())
for case in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	p = True
	c = 0
	for x in range(n):
		if arr[x] == x + 1:
			p = True
		else:
			c += int(p)
			p = False
		if c >= 2:
			break
	if c >= 2:
		print(2)
	elif c == 1:
		print(1)
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	elif a == sorted(a, reverse=True):
		print(1)
	else:
		d = [0] * n
		for i in range(n):
			if a[i] == i + 1:
				d[i] = 1
		(beg, end) = ([], [])
		for i in range(n):
			if d[i] == 1:
				beg.append(i)
			else:
				break
		for i in range(n - 1, -1, -1):
			if d[i] == 1:
				end.append(i)
			else:
				break
		flag = False
		for i in range(n):
			if d[i] == 1 and i not in beg and (i not in end):
				flag = True
				break
		if flag:
			print(2)
		else:
			print(1)


import sys
input = sys.stdin.readline
from collections import *
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if a == [i + 1 for i in range(n)]:
		print(0)
	else:
		l = []
		for i in range(n):
			if a[i] != i + 1:
				l.append(i)
		for i in range(1, len(l)):
			if l[i] != l[i - 1] + 1:
				print(2)
				break
		else:
			print(1)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	not_matching = [i for (i, ai) in enumerate(a) if i + 1 != ai]
	if len(not_matching) == 0:
		print(0)
	elif not_matching[-1] - not_matching[0] + 1 == len(not_matching):
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	cnt = 0
	a = list(map(int, input().split()))
	for i in range(n):
		if i + 1 != a[i]:
			cnt += 1
	if cnt == 0:
		print(0)
	elif cnt == n:
		print(1)
	else:
		c = 0
		for i in range(n):
			if i + 1 == a[i]:
				c += 1
			else:
				break
		for i in range(n - 1, -1, -1):
			if i + 1 == a[i]:
				c += 1
			else:
				break
		if c + cnt == n:
			print(1)
		else:
			print(2)


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	n = int(ii())
	data = idata()
	count = 0
	os = 0
	d = False
	for i in range(n):
		if data[i] == i + 1:
			count += 1
			d = False
		elif not d:
			d = True
			os += 1
	if count == n:
		print(0)
	elif count != 0 and os != 1:
		print(2)
	else:
		print(1)
	return
for t in range(int(ii())):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	i = 0
	j = n - 1
	while i < n and l[i] == i + 1:
		i += 1
	while j >= 0 and l[j] == j + 1:
		j -= 1
	ans = 0
	m = 0
	while i <= j:
		if l[i] != i + 1:
			ans += 1
		i += 1
		m += 1
	if ans == 0:
		print(0)
	elif ans == m:
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	index = []
	for j in range(n):
		if j + 1 != l[j]:
			index.append(j)
	if len(index) == 0:
		print(0)
	else:
		flag = 0
		for j in range(1, len(index)):
			if index[j] != index[j - 1] + 1:
				flag = 1
				break
		if flag == 1:
			print(2)
		else:
			print(1)


import sys
input = lambda : sys.stdin.readline().rstrip()
from math import gcd
lcm = lambda a, b: a * b // gcd(a, b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[i - 1] - i for i in range(1, n + 1)]
	ans = 0
	i = 0
	while i < n:
		if b[i] and ans == 0:
			ans += 1
		if b[i] == 0 and ans:
			j = i + 1
			while j < n and b[j] == 0:
				j += 1
			if j != n:
				ans += 1
				break
			i = j
		i += 1
	print(ans)


import math
t = int(input())

def alldiff(x):
	last = -1
	curr = -1
	for i in range(len(x)):
		if x[i] != i + 1:
			if curr == -1 and last == -1:
				(curr, last) = (i, i)
			elif last != -1:
				curr = i
				if last + 1 != curr:
					return 0
				last = i
	return 1
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	if b == a:
		print(0)
	elif alldiff(a):
		print(1)
	else:
		print(2)


t = int(input())
while t != 0:
	t -= 1
	n = int(input())
	a = [int(i) for i in input().split(' ')]
	a = [0] + a + [n + 1]
	i = 1
	k = 0
	while i != n + 2:
		if a[i] == i:
			if a[i - 1] != i - 1:
				k += 1
		i += 1
	if k == 0:
		print(0)
	elif k == 1:
		print(1)
	else:
		print(2)


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	flag = 0
	for i in range(len(a)):
		if i + 1 != a[i] and flag == 0:
			flag = 1
		if i + 1 == a[i] and flag == 1:
			flag = 2
		if i + 1 != a[i] and flag == 2:
			flag = 3
	if flag == 0:
		print(0)
	elif flag == 1 or flag == 2:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	input()
	a = ''.join((str(int(x == i + 1)) for (i, x) in enumerate(map(int, input().split())))).strip('1')
	print(2 if '1' in a else 1 if a else 0)


import math
n = int(input())
for i in range(n):
	t = int(input())
	l = list(map(int, input().split()))
	a = l[::1]
	a.sort()
	cnt = 0
	r = False
	for i in range(t):
		if a[i] == l[i]:
			if r:
				cnt += 1
			r = False
		else:
			r = True
	if cnt == 0:
		if r == False:
			print(0)
		if r == True:
			print(1)
	elif cnt == 1 and r == False:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	real = list(range(1, n + 1))
	if real == arr:
		print(0)
	else:
		i = 0
		while arr[i] == real[i]:
			i += 1
		j = n - 1
		while arr[j] == real[j]:
			j -= 1
		flag = True
		for x in range(i, j + 1):
			if arr[x] == real[x]:
				flag = False
				break
		if flag:
			print(1)
		else:
			print(2)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	rightPlace = 0
	for i in range(n):
		if a[i] == i + 1:
			rightPlace += 1
	if rightPlace == 0:
		print(1)
	elif rightPlace == n:
		print(0)
	else:
		for wrongStart in range(n):
			if a[wrongStart] != wrongStart + 1:
				break
		for wrongEnd in range(n - 1, -1, -1):
			if a[wrongEnd] != wrongEnd + 1:
				break
		ok = True
		for i in range(wrongStart, wrongEnd + 1):
			if a[i] == i + 1:
				ok = False
				print(2)
				break
		if ok:
			print(1)


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	n = II()
	a = [0] + LI() + [n + 1]
	ind = []
	for (i, v) in enumerate(a):
		if i == v:
			ind.append(i)
	ans = 0
	for i in range(1, len(ind)):
		if ind[i] - ind[i - 1] > 1:
			ans += 1
	print(2 if ans > 1 else ans)


import sys
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, sys.stdin.readline().strip().split()))
	j = 0
	while j < n and a[j] == j + 1:
		j += 1
	k = n
	while k > 0 and a[k - 1] == k:
		k -= 1
	op = 0
	for xx in range(j, k):
		if a[xx] == xx + 1:
			op += 1
	if op > 0:
		op = 1
	if j <= k:
		op += 1
	print(op)


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	if l == sorted(l):
		print(0)
	else:
		temp = []
		for i in range(n):
			if l[i] != i + 1:
				temp.append(i)
		if len(temp) == temp[-1] - temp[0] + 1:
			print(1)
		else:
			print(2)


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')
file = 1

def solve():
	for _ in range(ii()):
		n = ii()
		a = li()
		if a == sorted(a):
			print(0)
			continue
		f = 0
		l = 0
		r = n - 1
		for i in range(n):
			if a[i] != i + 1:
				l = i
				break
		for i in range(n - 1, -1, -1):
			if a[i] != i + 1:
				r = i
				break
		for i in range(l, r + 1):
			if a[i] == i + 1:
				f = 1
				break
		if f:
			print(2)
		else:
			print(1)
if file:
	if path.exists('input1.txt'):
		sys.stdin = open('input1.txt', 'r')
		sys.stdout = open('output1.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	n = inputnum()
	a = inputlist()
	wrong = 0
	firstwrong = False
	secondwrong = False
	for i in range(n):
		if i + 1 != a[i]:
			if not firstwrong:
				firstwrong = True
			elif firstwrong and a[i - 1] == i and (i > 1):
				secondwrong = True
			wrong += 1
	if wrong == 0:
		print(0)
	elif not secondwrong:
		print(1)
	else:
		print(2)


for _ in range(int(input())):
	n = int(input())
	data = list(map(int, input().split()))
	count = 0
	now = False
	for i in range(n):
		if i + 1 != data[i]:
			if now:
				continue
			count += 1
			now = True
		else:
			now = False
	if count >= 2:
		print(2)
	elif count == 1:
		print(1)
	else:
		print(0)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	k = 0
	l = 0
	r = 0
	for i in range(n):
		if a[i] == i + 1:
			k += 1
			if k == i + 1:
				l = k
			else:
				r += 1
		else:
			r = 0
	if k == n:
		ans = 0
	elif k == 0 or l + r == k:
		ans = 1
	else:
		ans = 2
	print(ans)


from sys import *
t = int(stdin.readline())
while t > 0:
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	dep = 0
	l = []
	for i in range(n):
		if i + 1 != arr[i]:
			dep = -1
			l.append(i + 1)
	if dep == 0:
		ans = 0
	else:
		s = 0
		for i in range(len(l) - 1):
			if l[i] != l[i + 1] - 1:
				s = 1
		if s == 0:
			ans = 1
		else:
			ans = 2
	print(ans)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	fl = 1
	for i in range(n):
		if a[i] == i + 1:
			continue
		fl = 0
	if fl:
		print(0)
		continue
	l = 0
	for i in range(n):
		if a[i] != i + 1:
			l = i
			break
	for i in range(n - 1, -1, -1):
		if a[i] != i + 1:
			r = i
			break
	fl = 1
	for i in range(l, r):
		if a[i] != i + 1:
			continue
		fl = 0
	if fl:
		print(1)
		continue
	print(2)


import sys
import math
from functools import reduce
import bisect

def getN():
	return int(input())

def getNM():
	return map(int, input().split())

def getList():
	return list(map(int, input().split()))

def input():
	return sys.stdin.readline().rstrip()

def index(a, x):
	i = bisect.bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	return False
for _ in range(int(input())):
	n = getN()
	arr = getList()
	x = []
	for i in range(n):
		if arr[i] != i + 1:
			x.append(i)
	if len(x) == 0:
		print(0)
	elif abs(x[-1] - x[0]) + 1 == len(x):
		print(1)
	else:
		print(2)


t = int(input(''))
mat = []
for i in range(t):
	x = int(input(''))
	mat.append(list(map(int, input().split())))
for i in range(t):
	tst = mat[i]
	diff = []
	for j in range(len(tst)):
		tst[j] = tst[j] - 1
		if tst[j] != j:
			diff.append(j)
	cnt = 0
	if len(diff) != 0:
		cnt = 1
		for k in range(len(diff) - 1):
			if diff[k + 1] - diff[k] != 1:
				cnt = 2
	print(cnt)


import sys
import math

def solve():
	t = int(input())
	for tests in range(0, t):
		n = int(input())
		a = list(map(int, input().split()))
		cnt = 0
		isInc = True
		li = []
		for i in range(0, n):
			if i > 0 and a[i] < a[i - 1]:
				isInc = False
			if a[i] - 1 == i:
				li.append(i)
		if isInc == True:
			print(0)
		else:
			if len(li) > 0:
				cnt += 1 if li[0] > 0 else 0
			for i in range(1, len(li)):
				cnt += 1 if li[i - 1] + 1 <= li[i] - 1 else 0
			if len(li) > 0:
				cnt += 1 if li[len(li) - 1] < n - 1 else 0
			if len(li) == 0:
				cnt = 1
			print(min(2, cnt))

def main():
	solve()
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	offset = 0
	if a[0] == 1:
		for i in range(1, n):
			if a[i] != a[i - 1] + 1:
				del a[:i]
				offset = i
				break
	if a[-1] == n:
		for i in range(len(a) - 2, -1, -1):
			if a[i] != a[i + 1] - 1:
				del a[i + 1:]
				break
	zero = True
	one = True
	prev = 0
	for i in range(len(a)):
		if a[i] < prev:
			zero = False
		if a[i] - offset == i + 1:
			one = False
		prev = a[i]
	if zero:
		print(0)
	elif one:
		print(1)
	else:
		print(2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ct = 0
	i = 0
	while i < n:
		j = i + 1
		if a[i] != i + 1:
			while j < n and j != a[j] - 1:
				j += 1
			ct += 1
		i = j
	print(min(2, ct))


import sys
import math
from collections import defaultdict as dd
mod = 1000000007
T = 1
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	flg = 1
	for i in range(n):
		if l[i] != i + 1:
			flg = 0
			break
	if flg:
		print(0)
		continue
	else:
		ans = 0
		f = 0
		for i in range(n):
			if l[i] != i + 1:
				f = 1
			else:
				if f == 1:
					ans += 1
				f = 0
		if f == 1:
			ans += 1
		print(min(ans, 2))


t = int(input())
for _ in range(t):
	n = int(input())
	nums = list(map(lambda x: int(x) - 1, input().split()))
	answer = 0
	current_counter = 0
	left_border = 0
	right_border = n
	while left_border < len(nums) and nums[left_border] == left_border:
		left_border += 1
	while right_border >= -1 and nums[right_border - 1] == right_border - 1:
		right_border -= 1
	if left_border >= right_border:
		print(0)
		continue
	good_counter = 0
	for i in range(left_border, right_border):
		if nums[i] == i:
			good_counter += 1
	if good_counter == 0:
		print(1)
	else:
		print(2)


import sys
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	diff_pos = [a[i] - i - 1 for i in range(n)]
	non_zero_poss = []
	for (i, x) in enumerate(diff_pos):
		if x != 0:
			non_zero_poss.append(i)
	if len(non_zero_poss) == 0:
		print(0)
	elif len(non_zero_poss) == n or non_zero_poss[-1] - non_zero_poss[0] + 1 == len(non_zero_poss):
		print(1)
	else:
		print(2)
test_case = int(input())
for _ in range(test_case):
	solve()


import sys, math, random
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	t = 0
	for i in range(N):
		if A[i] != i + 1:
			t = 1
			break
	if t == 0:
		print(0)
	else:
		j = 0
		t = 0
		for i in range(N):
			if A[i] != i + 1:
				break
		j = i
		for i in range(j + 1, N):
			if A[i] == i + 1:
				break
		j = i
		for i in range(j + 1, N):
			if A[i] != i + 1:
				t = 1
				break
		if t == 0:
			print(1)
		else:
			print(2)


import sys
input = sys.stdin.buffer.readline
import os
from math import *
import copy
t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	brr = copy.deepcopy(arr)
	brr.sort()
	(var1, var2) = [0] * 2
	count = 0
	checkpos = True
	fp = -1
	lp = -1
	check1 = 0
	check2 = 0
	for i in range(n):
		if arr[i] != brr[i] and check1 == 0:
			fp = i
			check1 = 1
		if arr[n - i - 1] != brr[n - i - 1] and check2 == 0:
			lp = n - i
			check2 = 1
	if fp == -1 or lp == -1:
		print('0')
	else:
		for i in range(fp, lp):
			if arr[i] == brr[i]:
				if var1 == 1:
					count += 1
			else:
				var1 = 1
			if count > 0:
				break
		if count == 0:
			if var1 == 1:
				print('1')
			else:
				print('0')
		else:
			print('2')


import sys
import bisect as bi
import math
from collections import defaultdict as dd
import heapq
input = sys.stdin.readline
mo = 10 ** 9 + 7

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def pref(a, n, f):
	pre = [0] * n
	if f == 0:
		pre[0] = a[0]
		for i in range(1, n):
			pre[i] = a[i] + pre[i - 1]
	else:
		pre[-1] = a[-1]
		for i in range(n - 2, -1, -1):
			pre[i] = pre[i + 1] + a[i]
	return pre
maxint = 10 ** 24

def kadane(a, size):
	max_so_far = -maxint - 1
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far
for _ in range(inin()):
	n = inin()
	l = ain()
	a = sorted(l)
	c = 0
	grp = f = 0
	cg = [0] * n
	for i in range(n):
		if a[i] == l[i]:
			cg[i] = 1
			c += 1
	if c == n:
		ans = 0
	elif c == 0:
		ans = 1
	else:
		fi = cg.index(0)
		li = n - cg[::-1].index(0) - 1
		c = n - c
		if li - fi + 1 == c:
			ans = 1
		else:
			ans = 2
	print(ans)


import math
import bisect
import copy
import time
from collections import Counter
for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	for i in range(len(l)):
		if i + 1 == l[i]:
			l[i] = 0
		else:
			l[i] = 1
	ans = []
	f = True
	for i in range(len(l)):
		if l[i] == 1 and f:
			f = False
			ans.append(1)
		if l[i] == 0 and (not f):
			f = True
			ans.append(0)
	x = ans.count(1)
	if x == 0:
		print(0)
	if x == 1:
		print(1)
	if x > 1:
		print(2)


for i in range(int(input())):
	x = int(input())
	y = list(map(int, input().split(' ')))
	asdf = []
	for i in range(x):
		if y[i] != i + 1:
			asdf.append(i)
	ct = 1
	if len(asdf) == 0:
		ct = 0
	for i in range(len(asdf) - 1):
		if asdf[i] + 1 != asdf[i + 1]:
			ct += 1
	print(min(ct, 2))


def main():
	for __ in [0] * int(input()):
		N = int(input())
		(*A,) = map(int, input().split())
		B = sorted(A)
		cnt = 0
		pre = 1 if A[0] == B[0] else 0
		L = []
		for (a, b) in zip(A, B):
			flag = 1 if a == b else 0
			if flag == pre:
				cnt += 1
			else:
				if pre == 0:
					L.append(cnt)
				cnt = 1
			pre = flag
		if pre == 0:
			L.append(cnt)
		print(min(2, len(L)))
main()